1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
|
#
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pysnmp/license.html
#
import pysnmp.smi.error
from pysnmp import debug
from pysnmp.proto import errind
from pysnmp.proto import error
from pysnmp.proto import rfc1902
from pysnmp.proto import rfc1905
from pysnmp.proto import rfc3411
from pysnmp.proto.api import v2c # backend is always SMIv2 compliant
from pysnmp.proto.proxy import rfc2576
from pysnmp.smi import exval
# 3.2
class CommandResponderBase(object):
ACM_ID = 3 # default MIB access control method to use
SUPPORTED_PDU_TYPES = ()
SMI_ERROR_MAP = {
pysnmp.smi.error.TooBigError: 'tooBig',
# this should never bubble up, SNMP exception objects should be passed as values
pysnmp.smi.error.NoSuchNameError: 'noSuchName',
pysnmp.smi.error.BadValueError: 'badValue',
pysnmp.smi.error.ReadOnlyError: 'readOnly',
pysnmp.smi.error.GenError: 'genErr',
pysnmp.smi.error.NoAccessError: 'noAccess',
pysnmp.smi.error.WrongTypeError: 'wrongType',
pysnmp.smi.error.WrongLengthError: 'wrongLength',
pysnmp.smi.error.WrongEncodingError: 'wrongEncoding',
pysnmp.smi.error.WrongValueError: 'wrongValue',
pysnmp.smi.error.NoCreationError: 'noCreation',
pysnmp.smi.error.InconsistentValueError: 'inconsistentValue',
pysnmp.smi.error.ResourceUnavailableError: 'resourceUnavailable',
pysnmp.smi.error.CommitFailedError: 'commitFailed',
pysnmp.smi.error.UndoFailedError: 'undoFailed',
pysnmp.smi.error.AuthorizationError: 'authorizationError',
pysnmp.smi.error.NotWritableError: 'notWritable',
pysnmp.smi.error.InconsistentNameError: 'inconsistentName'
}
def __init__(self, snmpEngine, snmpContext, cbCtx=None):
snmpEngine.msgAndPduDsp.registerContextEngineId(
snmpContext.contextEngineId, self.SUPPORTED_PDU_TYPES, self.processPdu
)
self.snmpContext = snmpContext
self.cbCtx = cbCtx
self.__pendingReqs = {}
def close(self, snmpEngine):
snmpEngine.msgAndPduDsp.unregisterContextEngineId(
self.snmpContext.contextEngineId, self.SUPPORTED_PDU_TYPES
)
self.snmpContext = self.__pendingReqs = None
def releaseStateInformation(self, stateReference):
if stateReference in self.__pendingReqs:
del self.__pendingReqs[stateReference]
def sendVarBinds(self, snmpEngine, stateReference,
errorStatus, errorIndex, varBinds):
(messageProcessingModel,
securityModel,
securityName,
securityLevel,
contextEngineId,
contextName,
pduVersion,
PDU,
origPdu,
maxSizeResponseScopedPDU,
statusInformation) = self.__pendingReqs[stateReference]
v2c.apiPDU.setErrorStatus(PDU, errorStatus)
v2c.apiPDU.setErrorIndex(PDU, errorIndex)
v2c.apiPDU.setVarBinds(PDU, varBinds)
debug.logger & debug.FLAG_APP and debug.logger(
'sendVarBinds: stateReference %s, errorStatus %s, errorIndex %s, '
'varBinds %s' % (stateReference, errorStatus, errorIndex, varBinds))
self.sendPdu(snmpEngine, stateReference, PDU)
def sendPdu(self, snmpEngine, stateReference, PDU):
(messageProcessingModel,
securityModel,
securityName,
securityLevel,
contextEngineId,
contextName,
pduVersion,
_,
origPdu,
maxSizeResponseScopedPDU,
statusInformation) = self.__pendingReqs[stateReference]
# Agent-side API complies with SMIv2
if messageProcessingModel == 0:
PDU = rfc2576.v2ToV1(PDU, origPdu)
# 3.2.6
try:
snmpEngine.msgAndPduDsp.returnResponsePdu(
snmpEngine,
messageProcessingModel,
securityModel,
securityName,
securityLevel,
contextEngineId,
contextName,
pduVersion,
PDU,
maxSizeResponseScopedPDU,
stateReference,
statusInformation
)
except error.StatusInformation as exc:
debug.logger & debug.FLAG_APP and debug.logger(
'sendPdu: stateReference %s, statusInformation '
'%s' % (stateReference, exc))
snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols(
'__SNMPv2-MIB', 'snmpSilentDrops')
snmpSilentDrops.syntax += 1
_getRequestType = rfc1905.GetRequestPDU.tagSet
_getNextRequestType = rfc1905.GetNextRequestPDU.tagSet
_setRequestType = rfc1905.SetRequestPDU.tagSet
_counter64Type = rfc1902.Counter64.tagSet
def processPdu(self, snmpEngine, messageProcessingModel, securityModel,
securityName, securityLevel, contextEngineId, contextName,
pduVersion, PDU, maxSizeResponseScopedPDU, stateReference):
# Agent-side API complies with SMIv2
if messageProcessingModel == 0:
origPdu = PDU
PDU = rfc2576.v1ToV2(PDU)
else:
origPdu = None
# 3.2.1
if (PDU.tagSet not in rfc3411.READ_CLASS_PDUS and
PDU.tagSet not in rfc3411.WRITE_CLASS_PDUS):
raise error.ProtocolError('Unexpected PDU class %s' % PDU.tagSet)
# 3.2.2 --> no-op
# 3.2.4
rspPDU = v2c.apiPDU.getResponse(PDU)
statusInformation = {}
self.__pendingReqs[stateReference] = (
messageProcessingModel, securityModel, securityName,
securityLevel, contextEngineId, contextName, pduVersion,
rspPDU, origPdu, maxSizeResponseScopedPDU, statusInformation
)
# 3.2.5
varBinds = v2c.apiPDU.getVarBinds(PDU)
debug.logger & debug.FLAG_APP and debug.logger(
'processPdu: stateReference %s, varBinds %s' % (stateReference, varBinds))
self.initiateMgmtOperation(snmpEngine, stateReference, contextName, PDU)
@staticmethod
def _storeAccessContext(snmpEngine):
"""Copy received message metadata while it lasts"""
execCtx = snmpEngine.observer.getExecutionContext('rfc3412.receiveMessage:request')
return {
'securityModel': execCtx['securityModel'],
'securityName': execCtx['securityName'],
'securityLevel': execCtx['securityLevel'],
'contextName': execCtx['contextName'],
'pduType': execCtx['pdu'].getTagSet()
}
@classmethod
def verifyAccess(cls, viewType, varBind, **context):
name, val = varBind
snmpEngine = context['snmpEngine']
(securityModel,
securityName,
securityLevel,
contextName,
pduType) = (context['securityModel'],
context['securityName'],
context['securityLevel'],
context['contextName'],
context['pduType'])
try:
snmpEngine.accessControlModel[cls.ACM_ID].isAccessAllowed(
snmpEngine, securityModel, securityName,
securityLevel, viewType, contextName, name
)
# Map ACM errors onto SMI ones
except error.StatusInformation as exc:
statusInformation = exc
debug.logger & debug.FLAG_APP and debug.logger(
'__verifyAccess: name %s, statusInformation '
'%s' % (name, statusInformation))
errorIndication = statusInformation['errorIndication']
# 3.2.5...
if (errorIndication == errind.noSuchView or
errorIndication == errind.noAccessEntry or
errorIndication == errind.noGroupName):
raise pysnmp.smi.error.AuthorizationError(
name=name, idx=context.get('idx'))
elif errorIndication == errind.otherError:
raise pysnmp.smi.error.GenError(name=name, idx=context.get('idx'))
elif errorIndication == errind.noSuchContext:
snmpUnknownContexts, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols(
'__SNMP-TARGET-MIB', 'snmpUnknownContexts')
snmpUnknownContexts.syntax += 1
# Request REPORT generation
raise pysnmp.smi.error.GenError(
name=name, idx=context.get('idx'), oid=snmpUnknownContexts.name,
val=snmpUnknownContexts.syntax)
elif errorIndication == errind.notInView:
return True
else:
raise error.ProtocolError('Unknown ACM error %s' % errorIndication)
else:
# rfc2576: 4.1.2.1
if (securityModel == 1 and val is not None and
cls._counter64Type == val.getTagSet() and
cls._getNextRequestType == pduType):
# This will cause MibTree to skip this OID-value
raise pysnmp.smi.error.NoAccessError(name=name, idx=context.get('idx'))
def _getMgmtFun(self, contextName):
return lambda *args, **kwargs: None
def _mapSmiErrors(self, varBinds, **context):
errorIndication = None
errorStatus = errorIndex = 0
errors = context.get('errors')
if not errors:
return errorIndication, errorStatus, errorIndex, varBinds
# Take the latest exception
err = errors[-1]
if isinstance(err, pysnmp.smi.error.GenError):
errorIndication = str(err)
elif isinstance(err, pysnmp.smi.error.SmiError):
if isinstance(err, pysnmp.smi.error.TooBigError):
# rfc1905: 4.2.1.3
varBinds = []
errorStatus = self.SMI_ERROR_MAP.get(err.__class__, 'genErr')
try:
errorIndex = err['idx'] + 1
except IndexError:
errorIndex = len(varBinds) and 1 or 0
return errorIndication, errorStatus, errorIndex, varBinds
def completeMgmtOperation(self, varBinds, **context):
(errorIndication,
errorStatus, errorIndex,
varBinds) = self._mapSmiErrors(varBinds, **context)
stateReference = context['stateReference']
if errorIndication:
statusInformation = self.__pendingReqs[stateReference]['statusInformation']
try:
# Request REPORT generation
statusInformation['oid'] = errorIndication['oid']
statusInformation['val'] = errorIndication['val']
except KeyError:
pass
self.sendVarBinds(context['snmpEngine'], stateReference,
errorStatus, errorIndex, varBinds)
self.releaseStateInformation(stateReference)
def initiateMgmtOperation(self, snmpEngine, stateReference, contextName, PDU):
varBinds = v2c.apiPDU.getVarBinds(PDU)
mgmtFun = self._getMgmtFun(contextName)
context = dict(snmpEngine=snmpEngine,
stateReference=stateReference,
acFun=self.verifyAccess,
cbFun=self.completeMgmtOperation,
cbCtx=self.cbCtx)
context.update(self._storeAccessContext(snmpEngine))
mgmtFun(*varBinds, **context)
class GetCommandResponder(CommandResponderBase):
SUPPORTED_PDU_TYPES = (rfc1905.GetRequestPDU.tagSet,)
# rfc1905: 4.2.1
def _getMgmtFun(self, contextName):
return self.snmpContext.getMibInstrum(contextName).readMibObjects
class NextCommandResponder(CommandResponderBase):
SUPPORTED_PDU_TYPES = (rfc1905.GetNextRequestPDU.tagSet,)
# rfc1905: 4.2.2
def _getMgmtFun(self, contextName):
return self.snmpContext.getMibInstrum(contextName).readNextMibObjects
def _getManagedObjectsInstances(self, varBinds, **context):
"""Iterate over Managed Objects fulfilling SNMP query.
Returns
-------
:py:class:`list` - List of Managed Objects Instances to respond with or
`None` to indicate that not all objects have been gathered
so far.
"""
rspVarBinds = context['rspVarBinds']
varBindsMap = context['varBindsMap']
rtrVarBinds = []
for idx, varBind in enumerate(varBinds):
name, val = varBind
if (exval.noSuchObject.isSameTypeWith(val) or
exval.noSuchInstance.isSameTypeWith(val)):
varBindsMap[len(rtrVarBinds)] = varBindsMap.pop(idx, idx)
rtrVarBinds.append(varBind)
else:
rspVarBinds[varBindsMap.pop(idx, idx)] = varBind
if rtrVarBinds:
snmpEngine = context['snmpEngine']
# Need to unwind stack, can't recurse any more
def callLater(*args):
snmpEngine.transportDispatcher.unregisterTimerCbFun(callLater)
mgmtFun = context['mgmtFun']
mgmtFun(*varBinds, **context)
snmpEngine.transportDispatcher.registerTimerCbFun(callLater, 0.01)
else:
return rspVarBinds
def completeMgmtOperation(self, varBinds, **context):
rspVarBinds = self._getManagedObjectsInstances(varBinds, **context)
if rspVarBinds:
CommandResponderBase.completeMgmtOperation(self, rspVarBinds, **context)
def initiateMgmtOperation(self, snmpEngine, stateReference, contextName, PDU):
varBinds = v2c.apiPDU.getVarBinds(PDU)
mgmtFun = self._getMgmtFun(contextName)
context = dict(snmpEngine=snmpEngine,
stateReference=stateReference,
acFun=self.verifyAccess,
cbFun=self.completeMgmtOperation,
cbCtx=self.cbCtx,
rspVarBinds=varBinds[:],
varBindsMap={},
mgmtFun=mgmtFun)
context.update(self._storeAccessContext(snmpEngine))
mgmtFun(*varBinds, **context)
class BulkCommandResponder(NextCommandResponder):
SUPPORTED_PDU_TYPES = (rfc1905.GetBulkRequestPDU.tagSet,)
MAX_VAR_BINDS = 64
def _completeNonRepeaters(self, varBinds, **context):
mgmtFun = context['mgmtFun']
if not varBinds:
# No non-repeaters requested, proceed with repeaters
mgmtFun(*context['reqVarBinds'],
**dict(context, cbFun=self.completeMgmtOperation,
varBinds=context['reqVarBinds'][:]))
return
rspVarBinds = self._getManagedObjectsInstances(varBinds, **context)
if rspVarBinds:
context['allVarBinds'].extend(rspVarBinds)
if context['counters']['M'] and context['counters']['R']:
rspVarBinds = self._getManagedObjectsInstances(varBinds, **context)
if rspVarBinds:
# Done with non-repeaters, proceed with repeaters
mgmtFun(*context['reqVarBinds'],
**dict(context,
cbFun=self.completeMgmtOperation,
varBindsMap={},
rspVarBinds=context['reqVarBinds'][:]))
return
else:
CommandResponderBase.completeMgmtOperation(self, context['allVarBinds'], **context)
def completeMgmtOperation(self, varBinds, **context):
rspVarBinds = self._getManagedObjectsInstances(varBinds, **context)
if rspVarBinds:
context['counters']['M'] -= 1
context['allVarBinds'].extend(rspVarBinds)
eom = all(exval.endOfMibView.isSameTypeWith(value) for name, value in rspVarBinds)
if not eom and context['counters']['M'] and context['counters']['R']:
snmpEngine = context['snmpEngine']
# Need to unwind stack, can't recurse any more
def callLater(*args):
snmpEngine.transportDispatcher.unregisterTimerCbFun(callLater)
mgmtFun = context['mgmtFun']
reqVarBinds = varBinds[-context['counters']['R']:]
mgmtFun(*reqVarBinds,
**dict(context, cbFun=self.completeMgmtOperation,
varBindsMap={}, rspVarBinds=reqVarBinds[:]))
snmpEngine.transportDispatcher.registerTimerCbFun(callLater, 0.01)
else:
CommandResponderBase.completeMgmtOperation(self, context['allVarBinds'], **context)
# rfc1905: 4.2.3
def initiateMgmtOperation(self, snmpEngine, stateReference, contextName, PDU):
nonRepeaters = v2c.apiBulkPDU.getNonRepeaters(PDU)
if nonRepeaters < 0:
nonRepeaters = 0
maxRepetitions = v2c.apiBulkPDU.getMaxRepetitions(PDU)
if maxRepetitions < 0:
maxRepetitions = 0
varBinds = v2c.apiPDU.getVarBinds(PDU)
N = min(int(nonRepeaters), len(varBinds))
M = int(maxRepetitions)
R = max(len(varBinds) - N, 0)
if R:
M = min(M, self.MAX_VAR_BINDS // R)
debug.logger & debug.FLAG_APP and debug.logger(
'initiateMgmtOperation: N %d, M %d, R %d' % (N, M, R))
mgmtFun = self._getMgmtFun(contextName)
context = dict(snmpEngine=snmpEngine,
stateReference=stateReference,
contextName=contextName,
acFun=self.verifyAccess,
cbFun=self._completeNonRepeaters,
cbCtx=self.cbCtx,
reqVarBinds=varBinds[N:],
counters={'M': M, 'R': R},
rspVarBinds=varBinds[N:],
allVarBinds=[],
varBindsMap={},
mgmtFun=mgmtFun)
context.update(self._storeAccessContext(snmpEngine))
mgmtFun(*varBinds[:N], **context)
class SetCommandResponder(CommandResponderBase):
SUPPORTED_PDU_TYPES = (rfc1905.SetRequestPDU.tagSet,)
SMI_ERROR_MAP = CommandResponderBase.SMI_ERROR_MAP.copy()
# turn missing OIDs into access denial
SMI_ERROR_MAP[pysnmp.smi.error.NoSuchObjectError] = 'notWritable'
SMI_ERROR_MAP[pysnmp.smi.error.NoSuchInstanceError] = 'notWritable'
# rfc1905: 4.2.5.1-13
def _getMgmtFun(self, contextName):
return self.snmpContext.getMibInstrum(contextName).writeMibObjects
|