Esempio n. 1
0
 def testCount(self):
     self.s1.clear()
     for x in ['abc', 'def', 'abc']:
         self.s1.append(x)
     assert self.s1.count(str2octs('abc')) == 2
     assert self.s1.count(str2octs('def')) == 1
     assert self.s1.count(str2octs('ghi')) == 0
Esempio n. 2
0
 def testSort(self):
     self.s1.clear()
     self.s1[0] = 'b'
     self.s1[1] = 'a'
     assert list(self.s1) == [str2octs('b'), str2octs('a')]
     self.s1.sort()
     assert list(self.s1) == [str2octs('a'), str2octs('b')]
Esempio n. 3
0
 def testIndex(self):
     self.s1.clear()
     for x in ['abc', 'def', 'abc']:
         self.s1.append(x)
     assert self.s1.index(str2octs('abc')) == 0
     assert self.s1.index(str2octs('def')) == 1
     assert self.s1.index(str2octs('abc'), 1) == 2
Esempio n. 4
0
 def testUpdate(self):
     self.s1.clear()
     assert list(self.s1.values()) == [str2octs(''), str2octs(''), 34]
     self.s1.update(**{'name': 'abc', 'nick': 'def', 'age': 123})
     assert list(self.s1.items()) == [(x[0], str2octs(x[1])) for x in [('name', 'abc'), ('nick', 'def')]] + [('age', 123)]
     self.s1.update(('name', 'ABC'))
     assert list(self.s1.items()) == [(x[0], str2octs(x[1])) for x in [('name', 'ABC'), ('nick', 'def')]] + [('age', 123)]
     self.s1.update(name='CBA')
     assert list(self.s1.items()) == [(x[0], str2octs(x[1])) for x in [('name', 'CBA'), ('nick', 'def')]] + [('age', 123)]
Esempio n. 5
0
 def testExtend(self):
     self.s1.clear()
     self.s1.setComponentByPosition(0, univ.OctetString('abc'))
     assert len(self.s1) == 1
     self.s1.extend(['def', 'ghi'])
     assert len(self.s1) == 3
     assert list(self.s1) == [str2octs(x) for x in ['abc', 'def', 'ghi']]
Esempio n. 6
0
 def testOuterByTypeWithInstanceValue(self):
     self.s1.setComponentByType(
         univ.OctetString.tagSet, univ.OctetString('abc')
     )
     assert self.s1.getComponentByType(
         univ.OctetString.tagSet
     ) == str2octs('abc')
Esempio n. 7
0
def searchRecordByOid(oid, fileObj, textParser, eol=str2octs('\n')):
    lo = mid = 0; prev_mid = -1
    fileObj.seek(0, 2)
    hi = sz = fileObj.tell()
    while lo < hi:
        mid = (lo+hi)//2
        fileObj.seek(mid)
        while mid:
            c = fileObj.read(1)
            if c == eol:
                mid = mid + 1
                break
            mid = mid - 1    # pivot stepping back in search for full line
            fileObj.seek(mid)
        if mid == prev_mid:  # loop condition due to stepping back pivot
            break
        if mid >= sz:
            return sz
        line, _, skippedOffset = getRecord(fileObj)
        if not line:
            return hi
        midval, _ = textParser.evaluate(line, oidOnly=True)
        if midval < oid:
            lo = mid + skippedOffset + len(line)
        elif midval > oid:
            hi = mid
        else:
            return mid
        prev_mid = mid
    if lo == mid:
        return lo
    else:
        return hi
Esempio n. 8
0
 def testIndefModeChunkedSubst(self):
     assert decoder.decode(
         ints2octs((36, 128, 4, 4, 81, 117, 105, 99, 4, 4, 107, 32, 98, 114, 4, 4, 111, 119, 110, 32, 4, 3, 102, 111,
                    120, 0, 0)),
         substrateFun=lambda a, b, c: (b, str2octs(''))
     ) == (ints2octs(
         (4, 4, 81, 117, 105, 99, 4, 4, 107, 32, 98, 114, 4, 4, 111, 119, 110, 32, 4, 3, 102, 111, 120, 0, 0)), str2octs(''))
Esempio n. 9
0
 def testIndefModeChunked(self):
     assert decoder.decode(
         ints2octs(
             (
                 36,
                 128,
                 4,
                 4,
                 81,
                 117,
                 105,
                 99,
                 4,
                 4,
                 107,
                 32,
                 98,
                 114,
                 4,
                 4,
                 111,
                 119,
                 110,
                 32,
                 4,
                 3,
                 102,
                 111,
                 120,
                 0,
                 0,
             )
         )
     ) == (str2octs("Quick brown fox"), null)
Esempio n. 10
0
 def __searchOid(self, oid, eol=str2octs('\n')):
     lo = mid = 0; prev_mid = -1;
     self.__text.seek(0, 2)
     hi = sz = self.__text.tell()
     while lo < hi:
         mid = (lo+hi)//2
         self.__text.seek(mid)
         while mid:
             c = self.__text.read(1)
             if c == eol:
                 mid = mid + 1
                 break
             mid = mid - 1    # pivot stepping back in search for full line
             self.__text.seek(mid)
         if mid == prev_mid:  # loop condition due to stepping back pivot
             break
         if mid >= sz:
             return sz
         line = self.__text.readline()
         midval, _ = self.__textParser.evaluate(line, oidOnly=True)
         if midval < oid:
             lo = mid + len(line)
         elif midval > oid:
             hi = mid
         else:
             return mid
         prev_mid = mid
     if lo == mid:
         return lo
     else:
         return hi
Esempio n. 11
0
 def testAppend(self):
     self.s1.clear()
     self.s1.setComponentByPosition(0, univ.OctetString('abc'))
     assert len(self.s1) == 1
     self.s1.append('def')
     assert len(self.s1) == 2
     assert list(self.s1) == [str2octs(x) for x in ['abc', 'def']]
Esempio n. 12
0
 def testWithoutSchema(self):
     s = univ.SequenceOf().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 3))
     s2, r = decoder.decode(
         ints2octs((163, 15, 48, 13, 4, 11, 113, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110))
     )
     assert not r
     assert s2 == [str2octs('quick brown')]
     assert s.tagSet == s2.tagSet
Esempio n. 13
0
    def testTypeCheckOnAssignment(self):

        self.s.clear()

        self.s['blob'] = univ.Any(str2octs('xxx'))

        # this should succeed because Any is untagged and unconstrained
        self.s['blob'] = univ.Integer(123)
Esempio n. 14
0
    def testStaticDef(self):

        class SequenceOf(univ.SequenceOf):
            componentType = univ.OctetString('')

        s = SequenceOf()
        s[0] = 'abc'
        assert len(s) == 1
        assert s == [str2octs('abc')]
Esempio n. 15
0
    def testStaticDef(self):

        class Set(univ.Set):
            componentType = namedtype.NamedTypes(
                namedtype.NamedType('name', univ.OctetString('')),
                namedtype.OptionalNamedType('nick', univ.OctetString('')),
                namedtype.DefaultedNamedType('age', univ.Integer(34))
            )

        s = Set()
        s['name'] = 'abc'
        assert s['name'] == str2octs('abc')
Esempio n. 16
0
def getRecord(fileObj, lineNo=None, offset=0):
    line = fileObj.readline()
    if lineNo is not None and line: lineNo += 1
    while line:
        tline = line.strip()
        # skip comment or blank line
        if not tline or tline.startswith(str2octs('#')):
            offset += len(line)
            line = fileObj.readline()
            if lineNo is not None and line: lineNo += 1
        else:
            break
    return line, lineNo, offset
Esempio n. 17
0
 def testUpdate(self):
     s = univ.Sequence()
     assert not s
     s.setComponentByPosition(0, univ.OctetString('abc'))
     s.setComponentByPosition(1, univ.Integer(123))
     assert s
     assert list(s.keys()) == ['field-0', 'field-1']
     assert list(s.values()) == [str2octs('abc'), 123]
     assert list(s.items()) == [('field-0', str2octs('abc')), ('field-1', 123)]
     s['field-0'] = univ.OctetString('def')
     assert list(s.values()) == [str2octs('def'), 123]
     s['field-1'] = univ.OctetString('ghi')
     assert list(s.values()) == [str2octs('def'), str2octs('ghi')]
     try:
         s['field-2'] = univ.OctetString('xxx')
     except KeyError:
         pass
     else:
         assert False, 'unknown field at schema-less object tolerated'
     assert 'field-0' in s
     s.clear()
     assert 'field-0' not in s
Esempio n. 18
0
 def testSubtypeSpec(self):
     s = self.s1.clone(subtypeSpec=constraint.ConstraintsUnion(
         constraint.SingleValueConstraint(str2octs('abc'))
         ))
     try:
         s.setComponentByPosition(0, univ.OctetString('abc'))
     except:
         assert 0, 'constraint fails'
     try:
         s.setComponentByPosition(1, univ.OctetString('Abc'))
     except:
         pass
     else:
         assert 0, 'constraint fails'
Esempio n. 19
0
    def lookup(self, oid):
        """ Returns the record which oid is exactly the given one or None if the record doesn't exist """

        # Issue #4: Synchronizes access to the database
        self.__lock.acquire(True);
        try:
            oid, is_subtree, tag, val = self.__db[oid].split(str2octs(','), 3)
        finally:
            self.__lock.release();

        try:
            tag_class = self.str2class(tag);
        except Exception:
            logger.error ( 'Could not interpret tag %s', tag, exc_info=True );
            raise
        return univ.ObjectIdentifier(oid), is_subtree, tag_class, tag_class(val)
Esempio n. 20
0
 def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
     if value.isPlusInfinity():
         return int2oct(0x40), 0
     if value.isMinusInfinity():
         return int2oct(0x41), 0
     m, b, e = value
     if not m:
         return null, 0
     if b == 10:
         return str2octs('\x03%dE%s%d' % (m, e == 0 and '+' or '', e)), 0
     elif b == 2:
         fo = 0x80                 # binary enoding
         if m < 0:
             fo = fo | 0x40  # sign bit
             m = -m
         while int(m) != m: # drop floating point
             m *= 2
             e -= 1
         while m & 0x1 == 0: # mantissa normalization
             m >>= 1
             e += 1
         eo = null
         while e not in (0, -1):
             eo = int2oct(e&0xff) + eo
             e >>= 8
         if e == 0 and eo and oct2int(eo[0]) & 0x80:
             eo = int2oct(0) + eo
         n = len(eo)
         if n > 0xff:
             raise error.PyAsn1Error('Real exponent overflow')
         if n == 1:
             pass
         elif n == 2:
             fo |= 1
         elif n == 3:
             fo |= 2
         else:
             fo |= 3
             eo = int2oct(n//0xff+1) + eo
         po = null
         while m:
             po = int2oct(m&0xff) + po
             m >>= 8
         substrate = int2oct(fo) + eo + po
         return substrate, 0
     else:
         raise error.PyAsn1Error('Prohibited Real base %s' % b)
Esempio n. 21
0
 def testComponentConstraintsMatching(self):
     s = self.s1.clone()
     o = univ.OctetString().subtype(
         subtypeSpec=constraint.ConstraintsUnion(constraint.SingleValueConstraint(str2octs('cba'))))
     s.strictConstraints = True
     try:
         s.setComponentByName('name', o.clone('cba'))
     except PyAsn1Error:
         pass
     else:
         assert 0, 'inner supertype constraint allowed'
     s.strictConstraints = False
     try:
         s.setComponentByName('name', o.clone('cba'))
     except PyAsn1Error:
         assert 0, 'inner supertype constraint disallowed'
     else:
         pass
Esempio n. 22
0
 def testSubtypeSpec(self):
     s = self.s1.clone(subtypeSpec=constraint.ConstraintsUnion(
         constraint.SingleValueConstraint(str2octs('abc'))
     ))
     try:
         s.setComponentByPosition(0, univ.OctetString('abc'))
     except PyAsn1Error:
         assert 0, 'constraint fails'
     try:
         s.setComponentByPosition(1, univ.OctetString('Abc'))
     except PyAsn1Error:
         try:
             s.setComponentByPosition(1, univ.OctetString('Abc'),
                                      verifyConstraints=False)
         except PyAsn1Error:
             assert 0, 'constraint failes with verifyConstraints=True'
     else:
         assert 0, 'constraint fails'
Esempio n. 23
0
 def testComponentConstraintsMatching(self):
     s = self.s1.clone()
     o = univ.OctetString().subtype(
         subtypeSpec=constraint.ConstraintsUnion(constraint.SingleValueConstraint(str2octs('cba'))))
     s.strictConstraints = True  # This requires types equality
     try:
         s.setComponentByPosition(0, o.clone('cba'))
     except PyAsn1Error:
         pass
     else:
         assert 0, 'inner supertype constraint allowed'
     s.strictConstraints = False  # This requires subtype relationships
     try:
         s.setComponentByPosition(0, o.clone('cba'))
     except PyAsn1Error:
         assert 0, 'inner supertype constraint disallowed'
     else:
         pass
Esempio n. 24
0
    def encodeValue(self, value, encodeFun, **options):
        value.verifySizeSpec()
        substrate = null
        idx = len(value)
        if value.typeId == univ.Set.typeId:
            namedTypes = value.componentType
            comps = []
            compsMap = {}
            while idx > 0:
                idx -= 1
                if namedTypes:
                    if namedTypes[idx].isOptional and not value[idx].isValue:
                        continue
                    if namedTypes[idx].isDefaulted and value[idx] == namedTypes[idx].asn1Object:
                        continue

                comps.append(value[idx])
                compsMap[id(value[idx])] = namedTypes and namedTypes[idx].isOptional

            for comp in self._sortComponents(comps):
                options.update(ifNotEmpty=compsMap[id(comp)])
                substrate += encodeFun(comp, **options)
        else:
            components = [encodeFun(x, **options) for x in value]

            # sort by serialized and padded components
            if len(components) > 1:
                zero = str2octs('\x00')
                maxLen = max(map(len, components))
                paddedComponents = [
                    (x.ljust(maxLen, zero), x) for x in components
                ]
                paddedComponents.sort(key=lambda x: x[0])

                components = [x[1] for x in paddedComponents]

            substrate = null.join(components)

        return substrate, True, True
Esempio n. 25
0
    def encodeValue(self, value, asn1Spec, encodeFun, **options):
        if asn1Spec is None:
            value.verifySizeSpec()
        else:
            asn1Spec = asn1Spec.componentType

        components = [encodeFun(x, asn1Spec, **options)
                      for x in value]

        # sort by serialised and padded components
        if len(components) > 1:
            zero = str2octs('\x00')
            maxLen = max(map(len, components))
            paddedComponents = [
                (x.ljust(maxLen, zero), x) for x in components
                ]
            paddedComponents.sort(key=lambda x: x[0])

            components = [x[1] for x in paddedComponents]

        substrate = null.join(components)

        return substrate, True, True
Esempio n. 26
0
    def __init__(self, snmpEngineID=None, maxMessageSize=65507,
                 msgAndPduDsp=None):
        self.cache = {}

        self.observer = observer.MetaObserver()

        if msgAndPduDsp is None:
            self.msgAndPduDsp = MsgAndPduDispatcher()

        else:
            self.msgAndPduDsp = msgAndPduDsp

        mibBuilder = self.msgAndPduDsp.mibInstrumController.mibBuilder

        self.messageProcessingSubsystems = {
            SnmpV1MessageProcessingModel.MESSAGE_PROCESSING_MODEL_ID:
                SnmpV1MessageProcessingModel(),
            SnmpV2cMessageProcessingModel.MESSAGE_PROCESSING_MODEL_ID:
                SnmpV2cMessageProcessingModel(),
            SnmpV3MessageProcessingModel.MESSAGE_PROCESSING_MODEL_ID:
                SnmpV3MessageProcessingModel()
        }

        self.securityModels = {
            SnmpV1SecurityModel.SECURITY_MODEL_ID: SnmpV1SecurityModel(),
            SnmpV2cSecurityModel.SECURITY_MODEL_ID: SnmpV2cSecurityModel(),
            SnmpUSMSecurityModel.SECURITY_MODEL_ID: SnmpUSMSecurityModel()
        }

        self.accessControlModel = {
            void.Vacm.ACCESS_MODEL_ID: void.Vacm(),
            rfc3415.Vacm.ACCESS_MODEL_ID: rfc3415.Vacm()
        }

        self.transportDispatcher = None

        if self.msgAndPduDsp.mibInstrumController is None:
            raise error.PySnmpError('MIB instrumentation does not yet exist')

        snmpEngineMaxMessageSize, = mibBuilder.importSymbols(
            '__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize')

        snmpEngineMaxMessageSize.syntax = snmpEngineMaxMessageSize.syntax.clone(maxMessageSize)

        snmpEngineBoots, = mibBuilder.importSymbols(
            '__SNMP-FRAMEWORK-MIB', 'snmpEngineBoots')

        snmpEngineBoots.syntax += 1

        origSnmpEngineID, = mibBuilder.importSymbols(
            '__SNMP-FRAMEWORK-MIB', 'snmpEngineID')

        if snmpEngineID is None:
            self.snmpEngineID = origSnmpEngineID.syntax

        else:
            origSnmpEngineID.syntax = origSnmpEngineID.syntax.clone(snmpEngineID)
            self.snmpEngineID = origSnmpEngineID.syntax

            debug.logger & debug.FLAG_APP and debug.logger(
                'SnmpEngine: using custom SNMP Engine '
                'ID: %s' % self.snmpEngineID.prettyPrint())

            # Attempt to make some of snmp Engine settings persistent.
            # This should probably be generalized as a non-volatile MIB store.

            persistentPath = os.path.join(tempfile.gettempdir(), '__pysnmp',
                                          self.snmpEngineID.prettyPrint())

            debug.logger & debug.FLAG_APP and debug.logger(
                'SnmpEngine: using persistent directory: %s' % persistentPath)

            if not os.path.exists(persistentPath):
                try:
                    os.makedirs(persistentPath)

                except OSError:
                    return

            f = os.path.join(persistentPath, 'boots')

            try:
                snmpEngineBoots.syntax = snmpEngineBoots.syntax.clone(open(f).read())

            except Exception:
                pass

            try:
                snmpEngineBoots.syntax += 1

            except Exception:
                snmpEngineBoots.syntax = snmpEngineBoots.syntax.clone(1)

            try:
                fd, fn = tempfile.mkstemp(dir=persistentPath)
                os.write(fd, str2octs(snmpEngineBoots.syntax.prettyPrint()))
                os.close(fd)
                shutil.move(fn, f)

            except Exception as exc:
                debug.logger & debug.FLAG_APP and debug.logger(
                    'SnmpEngine: could not stored SNMP Engine Boots: %s' % exc)

            else:
                debug.logger & debug.FLAG_APP and debug.logger(
                    'SnmpEngine: stored SNMP Engine Boots: '
                    '%s' % snmpEngineBoots.syntax.prettyPrint())
Esempio n. 27
0
 def testDefModeChunked(self):
     assert decoder.decode(
         ints2octs((36, 23, 4, 4, 81, 117, 105, 99, 4, 4, 107, 32, 98, 114, 4, 4, 111, 119, 110, 32, 4, 3, 102, 111, 120))
         ) == (str2octs('Quick brown fox'), null)
Esempio n. 28
0
 def testIndefMode(self):
     assert decoder.decode(
         ints2octs((36, 128, 4, 15, 81, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110, 32, 102, 111, 120, 0, 0))
         ) == (str2octs('Quick brown fox'), null)
Esempio n. 29
0
 def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
     if value.isPlusInfinity():
         return int2oct(0x40), 0
     if value.isMinusInfinity():
         return int2oct(0x41), 0
     m, b, e = value
     if not m:
         return null, 0
     if b == 10:
         return str2octs('\x03%dE%s%d' % (m, e == 0 and '+' or '', e)), 0
     elif b == 2:
         fo = 0x80 # binary encoding
         ms, m, encbase, e = self._chooseEncBase(value)
         if ms < 0: # mantissa sign
             fo = fo | 0x40 # sign bit
         # exponenta & mantissa normalization
         if encbase == 2:
             while m & 0x1 == 0:
                 m >>= 1
                 e += 1
         elif encbase == 8:
             while m & 0x7 == 0:
                 m >>= 3
                 e += 1
             fo |= 0x10
         else: # encbase = 16
             while m & 0xf == 0:
                 m >>= 4
                 e += 1
             fo |= 0x20
         sf = 0 # scale factor
         while m & 0x1 == 0:
             m >>= 1
             sf += 1
         if sf > 3:
             raise error.PyAsn1Error('Scale factor overflow') # bug if raised
         fo |= sf << 2
         eo = null
         if e == 0 or e == -1:
             eo = int2oct(e&0xff)
         else: 
             while e not in (0, -1):
                 eo = int2oct(e&0xff) + eo
                 e >>= 8
             if e == 0 and eo and oct2int(eo[0]) & 0x80:
                 eo = int2oct(0) + eo
             if e == -1 and eo and not (oct2int(eo[0]) & 0x80):
                 eo = int2oct(0xff) + eo
         n = len(eo)
         if n > 0xff:
             raise error.PyAsn1Error('Real exponent overflow')
         if n == 1:
             pass
         elif n == 2:
             fo |= 1
         elif n == 3:
             fo |= 2
         else:
             fo |= 3
             eo = int2oct(n&0xff) + eo
         po = null
         while m:
             po = int2oct(m&0xff) + po
             m >>= 8
         substrate = int2oct(fo) + eo + po
         return substrate, 0
     else:
         raise error.PyAsn1Error('Prohibited Real base %s' % b)
Esempio n. 30
0
    def testTypeCheckOnAssignment(self):

        self.s.clear()

        self.s['blob'] = univ.Any(str2octs('xxx'))
        self.s['blob'] = univ.Integer(123)