desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Create a copy of a |ASN.1| type or object. Any parameters to the *subtype()* method will be added to the corresponding properties of the |ASN.1| object. Parameters value: :class:`tuple`, :class:`float` or |ASN.1| object Initialization value to pass to new ASN.1 object instead of inheriting one from the caller. implicitTag: :py:class:`~pyasn1.type.tag.Tag` Implicitly apply given ASN.1 tag object to caller\'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object\'s ASN.1 tag(s). explicitTag: :py:class:`~pyasn1.type.tag.Tag` Explicitly apply given ASN.1 tag object to caller\'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object\'s ASN.1 tag(s). subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing ASN.1 subtype constraint(s) to use in new object instead of inheriting from the caller Returns new instance of |ASN.1| type/value'
def subtype(self, value=noValue, implicitTag=None, explicitTag=None, subtypeSpec=None):
return base.AbstractSimpleAsn1Item.subtype(self, value, implicitTag, explicitTag)
'Indicate PLUS-INFINITY object value Returns : :class:`bool` :class:`True` if calling object represents plus infinity or :class:`False` otherwise.'
def isPlusInfinity(self):
return (self._value == self._plusInf)
'Indicate MINUS-INFINITY object value Returns : :class:`bool` :class:`True` if calling object represents minus infinity or :class:`False` otherwise.'
def isMinusInfinity(self):
return (self._value == self._minusInf)
'Return |ASN.1| type component value by position. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters idx : :class:`int` Component index (zero-based). Must either refer to an existing component or to N+1 component (of *componentType is set). In the latter case a new component type gets instantiated and appended to the |ASN.1| sequence. Returns : :py:class:`~pyasn1.type.base.PyAsn1Item` a pyasn1 object'
def getComponentByPosition(self, idx):
try: return self._componentValues[idx] except IndexError: self.setComponentByPosition(idx) return self._componentValues[idx]
'Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`) or list.append() (when idx == len(self)). Parameters idx: :class:`int` Component index (zero-based). Must either refer to existing component or to N+1 component. In the latter case a new component type gets instantiated (if *componentType* is set, or given ASN.1 object is taken otherwise) and appended to the |ASN.1| sequence. value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. verifyConstraints: :class:`bool` If `False`, skip constraints validation matchTags: :class:`bool` If `False`, skip component tags matching matchConstraints: :class:`bool` If `False`, skip component constraints matching Returns self Raises IndexError: When idx > len(self)'
def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True):
componentType = self._componentType try: currentValue = self._componentValues[idx] except IndexError: currentValue = None if (len(self._componentValues) < idx): raise error.PyAsn1Error('Component index out of range') if ((value is None) or (value is noValue)): if (componentType is not None): value = componentType.clone() elif (currentValue is None): raise error.PyAsn1Error('Component type not defined') elif (not isinstance(value, base.Asn1Item)): if ((componentType is not None) and isinstance(componentType, base.AbstractSimpleAsn1Item)): value = componentType.clone(value=value) elif ((currentValue is not None) and isinstance(currentValue, base.AbstractSimpleAsn1Item)): value = currentValue.clone(value=value) else: raise error.PyAsn1Error(('%s undefined component type' % componentType.__class__.__name__)) elif (componentType is not None): if self.strictConstraints: if (not componentType.isSameTypeWith(value, matchTags, matchConstraints)): raise error.PyAsn1Error(('Component value is tag-incompatible: %r vs %r' % (value, componentType))) elif (not componentType.isSuperTypeOf(value, matchTags, matchConstraints)): raise error.PyAsn1Error(('Component value is tag-incompatible: %r vs %r' % (value, componentType))) if (verifyConstraints and value.isValue): try: self._subtypeSpec(value, idx) except error.PyAsn1Error: (exType, exValue, exTb) = sys.exc_info() raise exType(('%s at %s' % (exValue, self.__class__.__name__))) if (currentValue is None): self._componentValues.append(value) else: self._componentValues[idx] = value return self
'Indicate if |ASN.1| object components represent ASN.1 type or ASN.1 value. The PyASN1 type objects can only participate in types comparison and serve as a blueprint for serialization codecs to resolve ambiguous types. The PyASN1 value objects can additionally participate in most of built-in Python operations. Returns : :class:`bool` :class:`True` if all |ASN.1| components represent value and type, :class:`False` if at least one |ASN.1| component represents just ASN.1 type.'
@property def isValue(self):
if (not self._componentValues): return False for componentValue in self._componentValues: if (not componentValue.isValue): return False return True
'Returns |ASN.1| type component by name. Equivalent to Python :class:`dict` subscription operation (e.g. `[]`). Parameters name : :class:`str` |ASN.1| type component name Returns : :py:class:`~pyasn1.type.base.PyAsn1Item` Instantiate |ASN.1| component type or return existing component value'
def getComponentByName(self, name):
return self.getComponentByPosition(self._componentType.getPositionByName(name))
'Assign |ASN.1| type component by name. Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`). Parameters name: :class:`str` |ASN.1| type component name value : :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. verifyConstraints: :class:`bool` If `False`, skip constraints validation matchTags: :class:`bool` If `False`, skip component tags matching matchConstraints: :class:`bool` If `False`, skip component constraints matching Returns self'
def setComponentByName(self, name, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True):
return self.setComponentByPosition(self._componentType.getPositionByName(name), value, verifyConstraints, matchTags, matchConstraints)
'Returns |ASN.1| type component by index. Equivalent to Python sequence subscription operation (e.g. `[]`). Parameters idx : :class:`int` Component index (zero-based). Must either refer to an existing component or (if *componentType* is set) new ASN.1 type object gets instantiated. Returns : :py:class:`~pyasn1.type.base.PyAsn1Item` a PyASN1 object'
def getComponentByPosition(self, idx):
try: componentValue = self._componentValues[idx] except IndexError: componentValue = None if (componentValue is None): self.setComponentByPosition(idx) return self._componentValues[idx]
'Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`). Parameters idx : :class:`int` Component index (zero-based). Must either refer to existing component (if *componentType* is set) or to N+1 component otherwise. In the latter case a new component of given ASN.1 type gets instantiated and appended to |ASN.1| sequence. value : :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. verifyConstraints : :class:`bool` If `False`, skip constraints validation matchTags: :class:`bool` If `False`, skip component tags matching matchConstraints: :class:`bool` If `False`, skip component constraints matching Returns self'
def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True):
componentType = self._componentType componentTypeLen = self._componentTypeLen try: currentValue = self._componentValues[idx] except IndexError: currentValue = None if componentTypeLen: if (componentTypeLen < idx): raise IndexError('component index out of range') self._componentValues = ([None] * componentTypeLen) if ((value is None) or (value is noValue)): if componentTypeLen: value = componentType.getTypeByPosition(idx).clone() elif (currentValue is None): raise error.PyAsn1Error('Component type not defined') elif (not isinstance(value, base.Asn1Item)): if componentTypeLen: subComponentType = componentType.getTypeByPosition(idx) if isinstance(subComponentType, base.AbstractSimpleAsn1Item): value = subComponentType.clone(value=value) else: raise error.PyAsn1Error(('%s can cast only scalar values' % componentType.__class__.__name__)) elif ((currentValue is not None) and isinstance(currentValue, base.AbstractSimpleAsn1Item)): value = currentValue.clone(value=value) else: raise error.PyAsn1Error(('%s undefined component type' % componentType.__class__.__name__)) elif ((matchTags or matchConstraints) and componentTypeLen): subComponentType = componentType.getTypeByPosition(idx) if (subComponentType is not None): if self.strictConstraints: if (not subComponentType.isSameTypeWith(value, matchTags, matchConstraints)): raise error.PyAsn1Error(('Component value is tag-incompatible: %r vs %r' % (value, componentType))) elif (not subComponentType.isSuperTypeOf(value, matchTags, matchConstraints)): raise error.PyAsn1Error(('Component value is tag-incompatible: %r vs %r' % (value, componentType))) if (verifyConstraints and value.isValue): try: self._subtypeSpec(value, idx) except error.PyAsn1Error: (exType, exValue, exTb) = sys.exc_info() raise exType(('%s at %s' % (exValue, self.__class__.__name__))) if componentTypeLen: self._componentValues[idx] = value elif (len(self._componentValues) == idx): self._componentValues.append(value) else: raise error.PyAsn1Error('Component index out of range') return self
'Indicate if |ASN.1| object components represent ASN.1 type or ASN.1 value. The PyASN1 type objects can only participate in types comparison and serve as a blueprint for serialization codecs to resolve ambiguous types. The PyASN1 value objects can additionally participate in most of built-in Python operations. Returns : :class:`bool` :class:`True` if all |ASN.1| components represent value and type, :class:`False` if at least one |ASN.1| component represents just ASN.1 type.'
@property def isValue(self):
componentType = self._componentType if componentType: for (idx, subComponentType) in enumerate(componentType.namedTypes): if (subComponentType.isDefaulted or subComponentType.isOptional): continue if ((not self._componentValues) or (self._componentValues[idx] is None) or (not self._componentValues[idx].isValue)): return False else: for componentValue in self._componentValues: if (not componentValue.isValue): return False return True
'Return an object representation string. Returns : :class:`str` Human-friendly object representation.'
def prettyPrint(self, scope=0):
scope += 1 representation = (self.__class__.__name__ + ':\n') for idx in range(len(self._componentValues)): if (self._componentValues[idx] is not None): representation += (' ' * scope) componentType = self.getComponentType() if (componentType is None): representation += '<no-name>' else: representation += componentType.getNameByPosition(idx) representation = ('%s=%s\n' % (representation, self._componentValues[idx].prettyPrint(scope))) return representation
'Returns |ASN.1| type component by ASN.1 tag. Parameters tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify one of |ASN.1| object component Returns : :py:class:`~pyasn1.type.base.PyAsn1Item` a pyasn1 object'
def getComponentByType(self, tagSet, innerFlag=False):
component = self.getComponentByPosition(self._componentType.getPositionByType(tagSet)) if (innerFlag and isinstance(component, Set)): return component.getComponent(innerFlag=True) else: return component
'Assign |ASN.1| type component by ASN.1 tag. Parameters tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify one of |ASN.1| object component value : :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. verifyConstraints : :class:`bool` If `False`, skip constraints validation matchTags: :class:`bool` If `False`, skip component tags matching matchConstraints: :class:`bool` If `False`, skip component constraints matching innerFlag: :class:`bool` If `True`, search for matching *tagSet* recursively. Returns self'
def setComponentByType(self, tagSet, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True, innerFlag=False):
idx = self._componentType.getPositionByType(tagSet) if innerFlag: componentType = self._componentType.getTypeByPosition(idx) if componentType.tagSet: return self.setComponentByPosition(idx, value, verifyConstraints, matchTags, matchConstraints) else: componentType = self.getComponentByPosition(idx) return componentType.setComponentByType(tagSet, value, verifyConstraints, matchTags, matchConstraints, innerFlag=innerFlag) else: return self.setComponentByPosition(idx, value, verifyConstraints, matchTags, matchConstraints)
'Assign |ASN.1| type component by position. Equivalent to Python sequence item assignment operation (e.g. `[]`). Parameters idx: :class:`int` Component index (zero-based). Must either refer to existing component or to N+1 component. In the latter case a new component type gets instantiated (if *componentType* is set, or given ASN.1 object is taken otherwise) and appended to the |ASN.1| sequence. value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. Once a new value is set to *idx* component, previous value is dropped. verifyConstraints : :class:`bool` If `False`, skip constraints validation matchTags: :class:`bool` If `False`, skip component tags matching matchConstraints: :class:`bool` If `False`, skip component constraints matching Returns self'
def setComponentByPosition(self, idx, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True):
oldIdx = self._currentIdx Set.setComponentByPosition(self, idx, value, verifyConstraints, matchTags, matchConstraints) self._currentIdx = idx if ((oldIdx is not None) and (oldIdx != idx)): self._componentValues[oldIdx] = None return self
'Return a :class:`~pyasn1.type.tag.TagSet` object of the currently initialized component or self (if |ASN.1| is tagged).'
@property def effectiveTagSet(self):
if self._tagSet: return self._tagSet else: component = self.getComponent() return component.effectiveTagSet
'"Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects contained within callee.'
@property def tagMap(self):
if self._tagSet: return Set.tagMap.fget(self) else: return Set.componentTagMap.fget(self)
'Return currently assigned component of the |ASN.1| object. Returns : :py:class:`~pyasn1.type.base.PyAsn1Item` a PyASN1 object'
def getComponent(self, innerFlag=0):
if (self._currentIdx is None): raise error.PyAsn1Error('Component not chosen') else: c = self._componentValues[self._currentIdx] if (innerFlag and isinstance(c, Choice)): return c.getComponent(innerFlag) else: return c
'Return the name of currently assigned component of the |ASN.1| object. Returns : :py:class:`str` |ASN.1| component name'
def getName(self, innerFlag=False):
if (self._currentIdx is None): raise error.PyAsn1Error('Component not chosen') else: if innerFlag: c = self._componentValues[self._currentIdx] if isinstance(c, Choice): return c.getName(innerFlag) return self._componentType.getNameByPosition(self._currentIdx)
'Indicate if |ASN.1| component is set and represents ASN.1 type or ASN.1 value. The PyASN1 type objects can only participate in types comparison and serve as a blueprint for serialization codecs to resolve ambiguous types. The PyASN1 value objects can additionally participate in most of built-in Python operations. Returns : :class:`bool` :class:`True` if |ASN.1| component is set and represent value and type, :class:`False` if |ASN.1| component is not set or it represents just ASN.1 type.'
@property def isValue(self):
if (self._currentIdx is None): return False return self._componentValues[self._currentIdx].isValue
'"Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping ASN.1 tags to ASN.1 objects contained within callee.'
@property def tagMap(self):
try: return self._tagMap except AttributeError: self._tagMap = tagmap.TagMap({self.tagSet: self}, {eoo.endOfOctets.tagSet: eoo.endOfOctets}, self) return self._tagMap
'Creates a copy of a |ASN.1| type or object. Any parameters to the *clone()* method will replace corresponding properties of the |ASN.1| object. Parameters value: :class:`unicode`, :class:`str`, :class:`bytes` or |ASN.1| object unicode object (Python 2) or string (Python 3), alternatively string (Python 2) or bytes (Python 3) representing octet-stream of serialized unicode string (note `encoding` parameter) or |ASN.1| class instance. tagSet: :py:class:`~pyasn1.type.tag.TagSet` Object representing non-default ASN.1 tag(s) subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s) encoding: :py:class:`str` Unicode codec ID to encode/decode :py:class:`unicode` (Python 2) or :py:class:`str` (Python 3) the payload when |ASN.1| object is used in octet-stream context. Returns new instance of |ASN.1| type/value'
def clone(self, value=noValue, tagSet=None, subtypeSpec=None, encoding=None, binValue=noValue, hexValue=noValue):
return univ.OctetString.clone(self, value, tagSet, subtypeSpec, encoding, binValue, hexValue)
'Creates a copy of a |ASN.1| type or object. Any parameters to the *subtype()* method will be added to the corresponding properties of the |ASN.1| object. Parameters value: :class:`unicode`, :class:`str`, :class:`bytes` or |ASN.1| object unicode object (Python 2) or string (Python 3), alternatively string (Python 2) or bytes (Python 3) representing octet-stream of serialized unicode string (note `encoding` parameter) or |ASN.1| class instance. implicitTag: :py:class:`~pyasn1.type.tag.Tag` Implicitly apply given ASN.1 tag object to caller\'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object\'s ASN.1 tag(s). explicitTag: :py:class:`~pyasn1.type.tag.Tag` Explicitly apply given ASN.1 tag object to caller\'s :py:class:`~pyasn1.type.tag.TagSet`, then use the result as new object\'s ASN.1 tag(s). subtypeSpec: :py:class:`~pyasn1.type.constraint.ConstraintsIntersection` Object representing non-default ASN.1 subtype constraint(s) encoding: :py:class:`str` Unicode codec ID to encode/decode :py:class:`unicode` (Python 2) or :py:class:`str` (Python 3) the payload when |ASN.1| object is used in octet-stream context. Returns new instance of |ASN.1| type/value'
def subtype(self, value=noValue, implicitTag=None, explicitTag=None, subtypeSpec=None, encoding=None, binValue=noValue, hexValue=noValue):
return univ.OctetString.subtype(self, value, implicitTag, explicitTag, subtypeSpec, encoding, binValue, hexValue)
'Return ASN.1 type object by its position in fields set. Parameters idx: :py:class:`int` Field index Returns ASN.1 type Raises : :class:`~pyasn1.error.PyAsn1Error` If given position is out of fields range'
def getTypeByPosition(self, idx):
try: return self.__namedTypes[idx].asn1Object except IndexError: raise error.PyAsn1Error('Type position out of range')
'Return field position by its ASN.1 type. Parameters tagSet: :class:`~pysnmp.type.tag.TagSet` ASN.1 tag set distinguishing one ASN.1 type from others. Returns : :py:class:`int` ASN.1 type position in fields set Raises : :class:`~pyasn1.error.PyAsn1Error` If *tagSet* is not present or ASN.1 types are not unique within callee *NamedTypes*'
def getPositionByType(self, tagSet):
try: return self.__tagToPosMap[tagSet] except KeyError: raise error.PyAsn1Error(('Type %s not found' % (tagSet,)))
'Return field name by its position in fields set. Parameters idx: :py:class:`idx` Field index Returns : :py:class:`str` Field name Raises : :class:`~pyasn1.error.PyAsn1Error` If given field name is not present in callee *NamedTypes*'
def getNameByPosition(self, idx):
try: return self.__namedTypes[idx].name except IndexError: raise error.PyAsn1Error('Type position out of range')
'Return field position by filed name. Parameters name: :py:class:`str` Field name Returns : :py:class:`int` Field position in fields set Raises : :class:`~pyasn1.error.PyAsn1Error` If *name* is not present or not unique within callee *NamedTypes*'
def getPositionByName(self, name):
try: return self.__nameToPosMap[name] except KeyError: raise error.PyAsn1Error(('Name %s not found' % (name,)))
'Return ASN.1 types that are allowed at or past given field position. Some ASN.1 serialization allow for skipping optional and defaulted fields. Some constructed ASN.1 types allow reordering of the fields. When recovering such objects it may be important to know which types can possibly be present at any given position in the field sets. Parameters idx: :py:class:`int` Field index Returns : :class:`~pyasn1.type.tagmap.TagMap` Map if ASN.1 types allowed at given field position Raises : :class:`~pyasn1.error.PyAsn1Error` If given position is out of fields range'
def getTagMapNearPosition(self, idx):
try: return self.__ambigiousTypes[idx].getTagMap() except KeyError: raise error.PyAsn1Error('Type position out of range')
'Return the closest field position where given ASN.1 type is allowed. Some ASN.1 serialization allow for skipping optional and defaulted fields. Some constructed ASN.1 types allow reordering of the fields. When recovering such objects it may be important to know at which field position, in field set, given *tagSet* is allowed at or past *idx* position. Parameters tagSet: :class:`~pyasn1.type.tag.TagSet` ASN.1 type which field position to look up idx: :py:class:`int` Field position at or past which to perform ASN.1 type look up Returns : :py:class:`int` Field position in fields set Raises : :class:`~pyasn1.error.PyAsn1Error` If *tagSet* is not present or not unique within callee *NamedTypes* or *idx* is out of fields range'
def getPositionNearType(self, tagSet, idx):
try: return (idx + self.__ambigiousTypes[idx].getPositionByType(tagSet)) except KeyError: raise error.PyAsn1Error('Type position out of range')
'Return the minimal TagSet among ASN.1 type in callee *NamedTypes*. Some ASN.1 types/serialization protocols require ASN.1 types to be arranged based on their numerical tag value. The *minTagSet* property returns that. Returns : :class:`~pyasn1.type.tagset.TagSet` Minimal TagSet among ASN.1 types in callee *NamedTypes*'
@property def minTagSet(self):
if (self.__minTagSet is None): for namedType in self.__namedTypes: asn1Object = namedType.asn1Object try: tagSet = asn1Object.getMinTagSet() except AttributeError: tagSet = asn1Object.tagSet if ((self.__minTagSet is None) or (tagSet < self.__minTagSet)): self.__minTagSet = tagSet return self.__minTagSet
'Create a *TagMap* object from tags and types recursively. Create a new :class:`~pyasn1.type.tagmap.TagMap` object by combining tags from *TagMap* objects of children types and associating them with their immediate child type. Example .. code-block:: python OuterType ::= CHOICE { innerType INTEGER Calling *.getTagMap()* on *OuterType* will yield a map like this: .. code-block:: python Integer.tagSet -> Choice Parameters unique: :py:class:`bool` If `True`, duplicate *TagSet* objects occurring while building new *TagMap* would cause error. Returns : :class:`~pyasn1.type.tagmap.TagMap` New *TagMap* holding *TagSet* object gathered from childen types.'
def getTagMap(self, unique=False):
if (unique not in self.__tagMap): presentTypes = {} skipTypes = {} defaultType = None for namedType in self.__namedTypes: tagMap = namedType.asn1Object.tagMap for tagSet in tagMap: if (unique and (tagSet in presentTypes)): raise error.PyAsn1Error(('Non-unique tagSet %s' % (tagSet,))) presentTypes[tagSet] = namedType.asn1Object skipTypes.update(tagMap.skipTypes) if (defaultType is None): defaultType = tagMap.defaultType elif (tagMap.defaultType is not None): raise error.PyAsn1Error(('Duplicate default ASN.1 type at %s' % (self,))) self.__tagMap[unique] = tagmap.TagMap(presentTypes, skipTypes, defaultType) return self.__tagMap[unique]
'Build the wrapper'
def __init__(self, library):
self._lib = ctypes.CDLL(library) (self._version, self._hexversion, self._cflags) = get_version(self._lib) self._libreSSL = self._version.startswith('LibreSSL') self.pointer = ctypes.pointer self.c_int = ctypes.c_int self.byref = ctypes.byref self.create_string_buffer = ctypes.create_string_buffer self.BN_new = self._lib.BN_new self.BN_new.restype = ctypes.c_void_p self.BN_new.argtypes = [] self.BN_free = self._lib.BN_free self.BN_free.restype = None self.BN_free.argtypes = [ctypes.c_void_p] self.BN_num_bits = self._lib.BN_num_bits self.BN_num_bits.restype = ctypes.c_int self.BN_num_bits.argtypes = [ctypes.c_void_p] self.BN_bn2bin = self._lib.BN_bn2bin self.BN_bn2bin.restype = ctypes.c_int self.BN_bn2bin.argtypes = [ctypes.c_void_p, ctypes.c_void_p] self.BN_bin2bn = self._lib.BN_bin2bn self.BN_bin2bn.restype = ctypes.c_void_p self.BN_bin2bn.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p] self.EC_KEY_free = self._lib.EC_KEY_free self.EC_KEY_free.restype = None self.EC_KEY_free.argtypes = [ctypes.c_void_p] self.EC_KEY_new_by_curve_name = self._lib.EC_KEY_new_by_curve_name self.EC_KEY_new_by_curve_name.restype = ctypes.c_void_p self.EC_KEY_new_by_curve_name.argtypes = [ctypes.c_int] self.EC_KEY_generate_key = self._lib.EC_KEY_generate_key self.EC_KEY_generate_key.restype = ctypes.c_int self.EC_KEY_generate_key.argtypes = [ctypes.c_void_p] self.EC_KEY_check_key = self._lib.EC_KEY_check_key self.EC_KEY_check_key.restype = ctypes.c_int self.EC_KEY_check_key.argtypes = [ctypes.c_void_p] self.EC_KEY_get0_private_key = self._lib.EC_KEY_get0_private_key self.EC_KEY_get0_private_key.restype = ctypes.c_void_p self.EC_KEY_get0_private_key.argtypes = [ctypes.c_void_p] self.EC_KEY_get0_public_key = self._lib.EC_KEY_get0_public_key self.EC_KEY_get0_public_key.restype = ctypes.c_void_p self.EC_KEY_get0_public_key.argtypes = [ctypes.c_void_p] self.EC_KEY_get0_group = self._lib.EC_KEY_get0_group self.EC_KEY_get0_group.restype = ctypes.c_void_p self.EC_KEY_get0_group.argtypes = [ctypes.c_void_p] self.EC_POINT_get_affine_coordinates_GFp = self._lib.EC_POINT_get_affine_coordinates_GFp self.EC_POINT_get_affine_coordinates_GFp.restype = ctypes.c_int self.EC_POINT_get_affine_coordinates_GFp.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] self.EC_KEY_set_private_key = self._lib.EC_KEY_set_private_key self.EC_KEY_set_private_key.restype = ctypes.c_int self.EC_KEY_set_private_key.argtypes = [ctypes.c_void_p, ctypes.c_void_p] self.EC_KEY_set_public_key = self._lib.EC_KEY_set_public_key self.EC_KEY_set_public_key.restype = ctypes.c_int self.EC_KEY_set_public_key.argtypes = [ctypes.c_void_p, ctypes.c_void_p] self.EC_KEY_set_group = self._lib.EC_KEY_set_group self.EC_KEY_set_group.restype = ctypes.c_int self.EC_KEY_set_group.argtypes = [ctypes.c_void_p, ctypes.c_void_p] self.EC_POINT_set_affine_coordinates_GFp = self._lib.EC_POINT_set_affine_coordinates_GFp self.EC_POINT_set_affine_coordinates_GFp.restype = ctypes.c_int self.EC_POINT_set_affine_coordinates_GFp.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] self.EC_POINT_new = self._lib.EC_POINT_new self.EC_POINT_new.restype = ctypes.c_void_p self.EC_POINT_new.argtypes = [ctypes.c_void_p] self.EC_POINT_free = self._lib.EC_POINT_free self.EC_POINT_free.restype = None self.EC_POINT_free.argtypes = [ctypes.c_void_p] self.BN_CTX_free = self._lib.BN_CTX_free self.BN_CTX_free.restype = None self.BN_CTX_free.argtypes = [ctypes.c_void_p] self.EC_POINT_mul = self._lib.EC_POINT_mul self.EC_POINT_mul.restype = None self.EC_POINT_mul.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] self.EC_KEY_set_private_key = self._lib.EC_KEY_set_private_key self.EC_KEY_set_private_key.restype = ctypes.c_int self.EC_KEY_set_private_key.argtypes = [ctypes.c_void_p, ctypes.c_void_p] if ((self._hexversion >= 269484032) and (not self._libreSSL)): self.EC_KEY_OpenSSL = self._lib.EC_KEY_OpenSSL self._lib.EC_KEY_OpenSSL.restype = ctypes.c_void_p self._lib.EC_KEY_OpenSSL.argtypes = [] self.EC_KEY_set_method = self._lib.EC_KEY_set_method self._lib.EC_KEY_set_method.restype = ctypes.c_int self._lib.EC_KEY_set_method.argtypes = [ctypes.c_void_p, ctypes.c_void_p] else: self.ECDH_OpenSSL = self._lib.ECDH_OpenSSL self._lib.ECDH_OpenSSL.restype = ctypes.c_void_p self._lib.ECDH_OpenSSL.argtypes = [] self.ECDH_set_method = self._lib.ECDH_set_method self._lib.ECDH_set_method.restype = ctypes.c_int self._lib.ECDH_set_method.argtypes = [ctypes.c_void_p, ctypes.c_void_p] self.BN_CTX_new = self._lib.BN_CTX_new self._lib.BN_CTX_new.restype = ctypes.c_void_p self._lib.BN_CTX_new.argtypes = [] self.ECDH_compute_key = self._lib.ECDH_compute_key self.ECDH_compute_key.restype = ctypes.c_int self.ECDH_compute_key.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p] self.EVP_CipherInit_ex = self._lib.EVP_CipherInit_ex self.EVP_CipherInit_ex.restype = ctypes.c_int self.EVP_CipherInit_ex.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] self.EVP_CIPHER_CTX_new = self._lib.EVP_CIPHER_CTX_new self.EVP_CIPHER_CTX_new.restype = ctypes.c_void_p self.EVP_CIPHER_CTX_new.argtypes = [] self.EVP_aes_128_cfb128 = self._lib.EVP_aes_128_cfb128 self.EVP_aes_128_cfb128.restype = ctypes.c_void_p self.EVP_aes_128_cfb128.argtypes = [] self.EVP_aes_256_cfb128 = self._lib.EVP_aes_256_cfb128 self.EVP_aes_256_cfb128.restype = ctypes.c_void_p self.EVP_aes_256_cfb128.argtypes = [] self.EVP_aes_128_cbc = self._lib.EVP_aes_128_cbc self.EVP_aes_128_cbc.restype = ctypes.c_void_p self.EVP_aes_128_cbc.argtypes = [] self.EVP_aes_256_cbc = self._lib.EVP_aes_256_cbc self.EVP_aes_256_cbc.restype = ctypes.c_void_p self.EVP_aes_256_cbc.argtypes = [] self.EVP_aes_128_ofb = self._lib.EVP_aes_128_ofb self.EVP_aes_128_ofb.restype = ctypes.c_void_p self.EVP_aes_128_ofb.argtypes = [] self.EVP_aes_256_ofb = self._lib.EVP_aes_256_ofb self.EVP_aes_256_ofb.restype = ctypes.c_void_p self.EVP_aes_256_ofb.argtypes = [] self.EVP_bf_cbc = self._lib.EVP_bf_cbc self.EVP_bf_cbc.restype = ctypes.c_void_p self.EVP_bf_cbc.argtypes = [] self.EVP_bf_cfb64 = self._lib.EVP_bf_cfb64 self.EVP_bf_cfb64.restype = ctypes.c_void_p self.EVP_bf_cfb64.argtypes = [] self.EVP_rc4 = self._lib.EVP_rc4 self.EVP_rc4.restype = ctypes.c_void_p self.EVP_rc4.argtypes = [] if ((self._hexversion >= 269484032) and (not self._libreSSL)): self.EVP_CIPHER_CTX_reset = self._lib.EVP_CIPHER_CTX_reset self.EVP_CIPHER_CTX_reset.restype = ctypes.c_int self.EVP_CIPHER_CTX_reset.argtypes = [ctypes.c_void_p] else: self.EVP_CIPHER_CTX_cleanup = self._lib.EVP_CIPHER_CTX_cleanup self.EVP_CIPHER_CTX_cleanup.restype = ctypes.c_int self.EVP_CIPHER_CTX_cleanup.argtypes = [ctypes.c_void_p] self.EVP_CIPHER_CTX_free = self._lib.EVP_CIPHER_CTX_free self.EVP_CIPHER_CTX_free.restype = None self.EVP_CIPHER_CTX_free.argtypes = [ctypes.c_void_p] self.EVP_CipherUpdate = self._lib.EVP_CipherUpdate self.EVP_CipherUpdate.restype = ctypes.c_int self.EVP_CipherUpdate.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int] self.EVP_CipherFinal_ex = self._lib.EVP_CipherFinal_ex self.EVP_CipherFinal_ex.restype = ctypes.c_int self.EVP_CipherFinal_ex.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] self.EVP_DigestInit = self._lib.EVP_DigestInit self.EVP_DigestInit.restype = ctypes.c_int self._lib.EVP_DigestInit.argtypes = [ctypes.c_void_p, ctypes.c_void_p] self.EVP_DigestInit_ex = self._lib.EVP_DigestInit_ex self.EVP_DigestInit_ex.restype = ctypes.c_int self._lib.EVP_DigestInit_ex.argtypes = (3 * [ctypes.c_void_p]) self.EVP_DigestUpdate = self._lib.EVP_DigestUpdate self.EVP_DigestUpdate.restype = ctypes.c_int self.EVP_DigestUpdate.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int] self.EVP_DigestFinal = self._lib.EVP_DigestFinal self.EVP_DigestFinal.restype = ctypes.c_int self.EVP_DigestFinal.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] self.EVP_DigestFinal_ex = self._lib.EVP_DigestFinal_ex self.EVP_DigestFinal_ex.restype = ctypes.c_int self.EVP_DigestFinal_ex.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] self.ECDSA_sign = self._lib.ECDSA_sign self.ECDSA_sign.restype = ctypes.c_int self.ECDSA_sign.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p] self.ECDSA_verify = self._lib.ECDSA_verify self.ECDSA_verify.restype = ctypes.c_int self.ECDSA_verify.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p] if ((self._hexversion >= 269484032) and (not self._libreSSL)): self.EVP_MD_CTX_new = self._lib.EVP_MD_CTX_new self.EVP_MD_CTX_new.restype = ctypes.c_void_p self.EVP_MD_CTX_new.argtypes = [] self.EVP_MD_CTX_reset = self._lib.EVP_MD_CTX_reset self.EVP_MD_CTX_reset.restype = None self.EVP_MD_CTX_reset.argtypes = [ctypes.c_void_p] self.EVP_MD_CTX_free = self._lib.EVP_MD_CTX_free self.EVP_MD_CTX_free.restype = None self.EVP_MD_CTX_free.argtypes = [ctypes.c_void_p] self.EVP_sha1 = self._lib.EVP_sha1 self.EVP_sha1.restype = ctypes.c_void_p self.EVP_sha1.argtypes = [] self.digest_ecdsa_sha1 = self.EVP_sha1 else: self.EVP_MD_CTX_create = self._lib.EVP_MD_CTX_create self.EVP_MD_CTX_create.restype = ctypes.c_void_p self.EVP_MD_CTX_create.argtypes = [] self.EVP_MD_CTX_init = self._lib.EVP_MD_CTX_init self.EVP_MD_CTX_init.restype = None self.EVP_MD_CTX_init.argtypes = [ctypes.c_void_p] self.EVP_MD_CTX_destroy = self._lib.EVP_MD_CTX_destroy self.EVP_MD_CTX_destroy.restype = None self.EVP_MD_CTX_destroy.argtypes = [ctypes.c_void_p] self.EVP_ecdsa = self._lib.EVP_ecdsa self._lib.EVP_ecdsa.restype = ctypes.c_void_p self._lib.EVP_ecdsa.argtypes = [] self.digest_ecdsa_sha1 = self.EVP_ecdsa self.RAND_bytes = self._lib.RAND_bytes self.RAND_bytes.restype = ctypes.c_int self.RAND_bytes.argtypes = [ctypes.c_void_p, ctypes.c_int] self.EVP_sha256 = self._lib.EVP_sha256 self.EVP_sha256.restype = ctypes.c_void_p self.EVP_sha256.argtypes = [] self.i2o_ECPublicKey = self._lib.i2o_ECPublicKey self.i2o_ECPublicKey.restype = ctypes.c_void_p self.i2o_ECPublicKey.argtypes = [ctypes.c_void_p, ctypes.c_void_p] self.EVP_sha512 = self._lib.EVP_sha512 self.EVP_sha512.restype = ctypes.c_void_p self.EVP_sha512.argtypes = [] self.HMAC = self._lib.HMAC self.HMAC.restype = ctypes.c_void_p self.HMAC.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p] try: self.PKCS5_PBKDF2_HMAC = self._lib.PKCS5_PBKDF2_HMAC except: self.PKCS5_PBKDF2_HMAC = self._lib.PKCS5_PBKDF2_HMAC_SHA1 self.PKCS5_PBKDF2_HMAC.restype = ctypes.c_int self.PKCS5_PBKDF2_HMAC.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p] self._set_ciphers() self._set_curves()
'returns the length of a BN (OpenSSl API)'
def BN_num_bytes(self, x):
return int(((self.BN_num_bits(x) + 7) / 8))
'returns the OpenSSL cipher instance'
def get_cipher(self, name):
if (name not in self.cipher_algo): raise Exception('Unknown cipher') return self.cipher_algo[name]
'returns the id of a elliptic curve'
def get_curve(self, name):
if (name not in self.curves): raise Exception('Unknown curve') return self.curves[name]
'returns the name of a elliptic curve with his id'
def get_curve_by_id(self, id):
res = None for i in self.curves: if (self.curves[i] == id): res = i break if (res is None): raise Exception('Unknown curve') return res
'OpenSSL random function'
def rand(self, size):
buffer = self.malloc(0, size) while (self.RAND_bytes(buffer, size) != 1): import time time.sleep(1) return buffer.raw
'returns a create_string_buffer (ctypes)'
def malloc(self, data, size):
buffer = None if (data != 0): if ((sys.version_info.major == 3) and isinstance(data, type(''))): data = data.encode() buffer = self.create_string_buffer(data, size) else: buffer = self.create_string_buffer(size) return buffer
'For a normal and High level use, specifie pubkey, privkey (if you need) and the curve'
def __init__(self, pubkey=None, privkey=None, pubkey_x=None, pubkey_y=None, raw_privkey=None, curve='sect283r1'):
if (type(curve) == str): self.curve = OpenSSL.get_curve(curve) else: self.curve = curve if ((pubkey_x is not None) and (pubkey_y is not None)): self._set_keys(pubkey_x, pubkey_y, raw_privkey) elif (pubkey is not None): (curve, pubkey_x, pubkey_y, i) = ECC._decode_pubkey(pubkey) if (privkey is not None): (curve2, raw_privkey, i) = ECC._decode_privkey(privkey) if (curve != curve2): raise Exception('Bad ECC keys ...') self.curve = curve self._set_keys(pubkey_x, pubkey_y, raw_privkey) else: (self.privkey, self.pubkey_x, self.pubkey_y) = self._generate()
'static method, returns the list of all the curves available'
@staticmethod def get_curves():
return OpenSSL.curves.keys()
'High level function which returns : curve(2) + len_of_pubkeyX(2) + pubkeyX + len_of_pubkeyY + pubkeyY'
def get_pubkey(self):
return ''.join((pack('!H', self.curve), pack('!H', len(self.pubkey_x)), self.pubkey_x, pack('!H', len(self.pubkey_y)), self.pubkey_y))
'High level function which returns curve(2) + len_of_privkey(2) + privkey'
def get_privkey(self):
return ''.join((pack('!H', self.curve), pack('!H', len(self.privkey)), self.privkey))
'High level function. Compute public key with the local private key and returns a 512bits shared key'
def get_ecdh_key(self, pubkey):
(curve, pubkey_x, pubkey_y, i) = ECC._decode_pubkey(pubkey) if (curve != self.curve): raise Exception('ECC keys must be from the same curve !') return sha512(self.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
'Check the public key and the private key. The private key is optional (replace by None)'
def check_key(self, privkey, pubkey):
(curve, pubkey_x, pubkey_y, i) = ECC._decode_pubkey(pubkey) if (privkey is None): raw_privkey = None curve2 = curve else: (curve2, raw_privkey, i) = ECC._decode_privkey(privkey) if (curve != curve2): raise Exception('Bad public and private key') return self.raw_check_key(raw_privkey, pubkey_x, pubkey_y, curve)
'Sign the input with ECDSA method and returns the signature'
def sign(self, inputb, digest_alg=OpenSSL.digest_ecdsa_sha1):
try: size = len(inputb) buff = OpenSSL.malloc(inputb, size) digest = OpenSSL.malloc(0, 64) if ((OpenSSL._hexversion > 269484032) and (not OpenSSL._libreSSL)): md_ctx = OpenSSL.EVP_MD_CTX_new() else: md_ctx = OpenSSL.EVP_MD_CTX_create() dgst_len = OpenSSL.pointer(OpenSSL.c_int(0)) siglen = OpenSSL.pointer(OpenSSL.c_int(0)) sig = OpenSSL.malloc(0, 151) key = OpenSSL.EC_KEY_new_by_curve_name(self.curve) if (key == 0): raise Exception('[OpenSSL] EC_KEY_new_by_curve_name FAIL ...') priv_key = OpenSSL.BN_bin2bn(self.privkey, len(self.privkey), 0) pub_key_x = OpenSSL.BN_bin2bn(self.pubkey_x, len(self.pubkey_x), 0) pub_key_y = OpenSSL.BN_bin2bn(self.pubkey_y, len(self.pubkey_y), 0) if (OpenSSL.EC_KEY_set_private_key(key, priv_key) == 0): raise Exception('[OpenSSL] EC_KEY_set_private_key FAIL ...') group = OpenSSL.EC_KEY_get0_group(key) pub_key = OpenSSL.EC_POINT_new(group) if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(group, pub_key, pub_key_x, pub_key_y, 0) == 0): raise Exception('[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...') if (OpenSSL.EC_KEY_set_public_key(key, pub_key) == 0): raise Exception('[OpenSSL] EC_KEY_set_public_key FAIL ...') if (OpenSSL.EC_KEY_check_key(key) == 0): raise Exception('[OpenSSL] EC_KEY_check_key FAIL ...') if ((OpenSSL._hexversion > 269484032) and (not OpenSSL._libreSSL)): OpenSSL.EVP_MD_CTX_new(md_ctx) else: OpenSSL.EVP_MD_CTX_init(md_ctx) OpenSSL.EVP_DigestInit_ex(md_ctx, digest_alg(), None) if (OpenSSL.EVP_DigestUpdate(md_ctx, buff, size) == 0): raise Exception('[OpenSSL] EVP_DigestUpdate FAIL ...') OpenSSL.EVP_DigestFinal_ex(md_ctx, digest, dgst_len) OpenSSL.ECDSA_sign(0, digest, dgst_len.contents, sig, siglen, key) if (OpenSSL.ECDSA_verify(0, digest, dgst_len.contents, sig, siglen.contents, key) != 1): raise Exception('[OpenSSL] ECDSA_verify FAIL ...') return sig.raw[:siglen.contents.value] finally: OpenSSL.EC_KEY_free(key) OpenSSL.BN_free(pub_key_x) OpenSSL.BN_free(pub_key_y) OpenSSL.BN_free(priv_key) OpenSSL.EC_POINT_free(pub_key) if ((OpenSSL._hexversion > 269484032) and (not OpenSSL._libreSSL)): OpenSSL.EVP_MD_CTX_free(md_ctx) else: OpenSSL.EVP_MD_CTX_destroy(md_ctx) pass
'Verify the signature with the input and the local public key. Returns a boolean'
def verify(self, sig, inputb, digest_alg=OpenSSL.digest_ecdsa_sha1):
try: bsig = OpenSSL.malloc(sig, len(sig)) binputb = OpenSSL.malloc(inputb, len(inputb)) digest = OpenSSL.malloc(0, 64) dgst_len = OpenSSL.pointer(OpenSSL.c_int(0)) if ((OpenSSL._hexversion > 269484032) and (not OpenSSL._libreSSL)): md_ctx = OpenSSL.EVP_MD_CTX_new() else: md_ctx = OpenSSL.EVP_MD_CTX_create() key = OpenSSL.EC_KEY_new_by_curve_name(self.curve) if (key == 0): raise Exception('[OpenSSL] EC_KEY_new_by_curve_name FAIL ...') pub_key_x = OpenSSL.BN_bin2bn(self.pubkey_x, len(self.pubkey_x), 0) pub_key_y = OpenSSL.BN_bin2bn(self.pubkey_y, len(self.pubkey_y), 0) group = OpenSSL.EC_KEY_get0_group(key) pub_key = OpenSSL.EC_POINT_new(group) if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(group, pub_key, pub_key_x, pub_key_y, 0) == 0): raise Exception('[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...') if (OpenSSL.EC_KEY_set_public_key(key, pub_key) == 0): raise Exception('[OpenSSL] EC_KEY_set_public_key FAIL ...') if (OpenSSL.EC_KEY_check_key(key) == 0): raise Exception('[OpenSSL] EC_KEY_check_key FAIL ...') if ((OpenSSL._hexversion > 269484032) and (not OpenSSL._libreSSL)): OpenSSL.EVP_MD_CTX_new(md_ctx) else: OpenSSL.EVP_MD_CTX_init(md_ctx) OpenSSL.EVP_DigestInit_ex(md_ctx, digest_alg(), None) if (OpenSSL.EVP_DigestUpdate(md_ctx, binputb, len(inputb)) == 0): raise Exception('[OpenSSL] EVP_DigestUpdate FAIL ...') OpenSSL.EVP_DigestFinal_ex(md_ctx, digest, dgst_len) ret = OpenSSL.ECDSA_verify(0, digest, dgst_len.contents, bsig, len(sig), key) if (ret == (-1)): return False elif (ret == 0): return False else: return True return False finally: OpenSSL.EC_KEY_free(key) OpenSSL.BN_free(pub_key_x) OpenSSL.BN_free(pub_key_y) OpenSSL.EC_POINT_free(pub_key) if ((OpenSSL._hexversion > 269484032) and (not OpenSSL._libreSSL)): OpenSSL.EVP_MD_CTX_free(md_ctx) else: OpenSSL.EVP_MD_CTX_destroy(md_ctx)
'Encrypt data with ECIES method using the public key of the recipient.'
@staticmethod def encrypt(data, pubkey, ephemcurve=None, ciphername='aes-256-cbc'):
(curve, pubkey_x, pubkey_y, i) = ECC._decode_pubkey(pubkey) return ECC.raw_encrypt(data, pubkey_x, pubkey_y, curve=curve, ephemcurve=ephemcurve, ciphername=ciphername)
'Decrypt data with ECIES method using the local private key'
def decrypt(self, data, ciphername='aes-256-cbc'):
blocksize = OpenSSL.get_cipher(ciphername).get_blocksize() iv = data[:blocksize] i = blocksize (curve, pubkey_x, pubkey_y, i2) = ECC._decode_pubkey(data[i:]) i += i2 ciphertext = data[i:(len(data) - 32)] i += len(ciphertext) mac = data[i:] key = sha512(self.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest() (key_e, key_m) = (key[:32], key[32:]) if (not equals(hmac_sha256(key_m, data[:(len(data) - 32)]), mac)): raise RuntimeError('Fail to verify data') ctx = Cipher(key_e, iv, 0, ciphername) return ctx.ciphering(ciphertext)
'do == 1 => Encrypt; do == 0 => Decrypt'
def __init__(self, key, iv, do, ciphername='aes-256-cbc'):
self.cipher = OpenSSL.get_cipher(ciphername) self.ctx = OpenSSL.EVP_CIPHER_CTX_new() if ((do == 1) or (do == 0)): k = OpenSSL.malloc(key, len(key)) IV = OpenSSL.malloc(iv, len(iv)) OpenSSL.EVP_CipherInit_ex(self.ctx, self.cipher.get_pointer(), 0, k, IV, do) else: raise Exception('RTFM ...')
'static method, returns all ciphers available'
@staticmethod def get_all_cipher():
return OpenSSL.cipher_algo.keys()
'Do update and final in one method'
def ciphering(self, input):
buff = self.update(input) return (buff + self.final())
'Internal method used to convert the utf-8 encoded bytestring into unicode. If the conversion fails, the socket will be closed.'
def _decode_bytes(self, bytestring):
if (not bytestring): return '' try: return bytestring.decode('utf-8') except UnicodeDecodeError: self.close(1007) raise
':returns: The utf-8 byte string equivalent of `text`.'
def _encode_bytes(self, text):
if (not isinstance(text, str)): text = text_type((text or '')) return text.encode('utf-8')
':returns: Whether the returned close code is a valid hybi return code.'
def _is_valid_close_code(self, code):
if (code < 1000): return False if (1004 <= code <= 1006): return False if (1012 <= code <= 1016): return False if (code == 1100): return False if (2000 <= code <= 2999): return False return True
'Called when a close frame has been decoded from the stream. :param header: The decoded `Header`. :param payload: The bytestring payload associated with the close frame.'
def handle_close(self, header, payload):
if (not payload): self.close(1000, None) return if (len(payload) < 2): raise ProtocolError('Invalid close frame: {0} {1}'.format(header, payload)) code = struct.unpack('!H', payload[:2])[0] payload = payload[2:] if payload: validator = Utf8Validator() val = validator.validate(payload) if (not val[0]): raise UnicodeError if (not self._is_valid_close_code(code)): raise ProtocolError('Invalid close code {0}'.format(code)) self.close(code, payload)
'Block until a full frame has been read from the socket. This is an internal method as calling this will not cleanup correctly if an exception is called. Use `receive` instead. :return: The header and payload as a tuple.'
def read_frame(self):
header = Header.decode_header(self.stream) if header.flags: raise ProtocolError if (not header.length): return (header, '') try: payload = self.raw_read(header.length) except socket.error: payload = '' except Exception: payload = '' if (len(payload) != header.length): raise WebSocketError('Unexpected EOF reading frame payload') if header.mask: payload = header.unmask_payload(payload) return (header, payload)
'Return the next text or binary message from the socket. This is an internal method as calling this will not cleanup correctly if an exception is called. Use `receive` instead.'
def read_message(self):
opcode = None message = bytearray() while True: (header, payload) = self.read_frame() f_opcode = header.opcode if (f_opcode in (self.OPCODE_TEXT, self.OPCODE_BINARY)): if opcode: raise ProtocolError('The opcode in non-fin frame is expected to be zero, got {0!r}'.format(f_opcode)) self.utf8validator.reset() self.utf8validate_last = (True, True, 0, 0) opcode = f_opcode elif (f_opcode == self.OPCODE_CONTINUATION): if (not opcode): raise ProtocolError('Unexpected frame with opcode=0') elif (f_opcode == self.OPCODE_PING): self.handle_ping(header, payload) continue elif (f_opcode == self.OPCODE_PONG): self.handle_pong(header, payload) continue elif (f_opcode == self.OPCODE_CLOSE): self.handle_close(header, payload) return else: raise ProtocolError('Unexpected opcode={0!r}'.format(f_opcode)) if (opcode == self.OPCODE_TEXT): self.validate_utf8(payload) message += payload if header.fin: break if (opcode == self.OPCODE_TEXT): self.validate_utf8(message) return self._decode_bytes(message) else: return message
'Read and return a message from the stream. If `None` is returned, then the socket is considered closed/errored.'
def receive(self):
if self.closed: self.current_app.on_close(MSG_ALREADY_CLOSED) raise WebSocketError(MSG_ALREADY_CLOSED) try: return self.read_message() except UnicodeError: self.close(1007) except ProtocolError: self.close(1002) except socket.timeout: self.close() self.current_app.on_close(MSG_CLOSED) except socket.error: self.close() self.current_app.on_close(MSG_CLOSED) return None
'Send a frame over the websocket with message as its payload'
def send_frame(self, message, opcode):
if self.closed: self.current_app.on_close(MSG_ALREADY_CLOSED) raise WebSocketError(MSG_ALREADY_CLOSED) if (not message): return if (opcode in (self.OPCODE_TEXT, self.OPCODE_PING)): message = self._encode_bytes(message) elif (opcode == self.OPCODE_BINARY): message = bytes(message) header = Header.encode_header(True, opcode, '', len(message), 0) try: self.raw_write((header + message)) except socket.error: raise WebSocketError(MSG_SOCKET_DEAD) except: raise
'Send a frame over the websocket with message as its payload'
def send(self, message, binary=None):
if (binary is None): binary = (not isinstance(message, string_types)) opcode = (self.OPCODE_BINARY if binary else self.OPCODE_TEXT) try: self.send_frame(message, opcode) except WebSocketError: self.current_app.on_close(MSG_SOCKET_DEAD) raise WebSocketError(MSG_SOCKET_DEAD)
'Close the websocket and connection, sending the specified code and message. The underlying socket object is _not_ closed, that is the responsibility of the initiator.'
def close(self, code=1000, message=''):
if self.closed: self.current_app.on_close(MSG_ALREADY_CLOSED) try: message = self._encode_bytes(message) self.send_frame(message, opcode=self.OPCODE_CLOSE) except WebSocketError: self.logger.debug('Failed to write closing frame -> closing socket') finally: self.logger.debug('Closed WebSocket') self.closed = True self.stream = None self.raw_write = None self.raw_read = None self.environ = None
'Decode a WebSocket header. :param stream: A file like object that can be \'read\' from. :returns: A `Header` instance.'
@classmethod def decode_header(cls, stream):
read = stream.read data = read(2) if (len(data) != 2): raise WebSocketError('Unexpected EOF while decoding header') (first_byte, second_byte) = struct.unpack('!BB', data) header = cls(fin=((first_byte & cls.FIN_MASK) == cls.FIN_MASK), opcode=(first_byte & cls.OPCODE_MASK), flags=(first_byte & cls.HEADER_FLAG_MASK), length=(second_byte & cls.LENGTH_MASK)) has_mask = ((second_byte & cls.MASK_MASK) == cls.MASK_MASK) if (header.opcode > 7): if (not header.fin): raise ProtocolError('Received fragmented control frame: {0!r}'.format(data)) if (header.length > 125): raise FrameTooLargeException('Control frame cannot be larger than 125 bytes: {0!r}'.format(data)) if (header.length == 126): data = read(2) if (len(data) != 2): raise WebSocketError('Unexpected EOF while decoding header') header.length = struct.unpack('!H', data)[0] elif (header.length == 127): data = read(8) if (len(data) != 8): raise WebSocketError('Unexpected EOF while decoding header') header.length = struct.unpack('!Q', data)[0] if has_mask: mask = read(4) if (len(mask) != 4): raise WebSocketError('Unexpected EOF while decoding header') header.mask = mask return header
'Encodes a WebSocket header. :param fin: Whether this is the final frame for this opcode. :param opcode: The opcode of the payload, see `OPCODE_*` :param mask: Whether the payload is masked. :param length: The length of the frame. :param flags: The RSV* flags. :return: A bytestring encoded header.'
@classmethod def encode_header(cls, fin, opcode, mask, length, flags):
first_byte = opcode second_byte = 0 extra = '' result = bytearray() if fin: first_byte |= cls.FIN_MASK if (flags & cls.RSV0_MASK): first_byte |= cls.RSV0_MASK if (flags & cls.RSV1_MASK): first_byte |= cls.RSV1_MASK if (flags & cls.RSV2_MASK): first_byte |= cls.RSV2_MASK if (length < 126): second_byte += length elif (length <= 65535): second_byte += 126 extra = struct.pack('!H', length) elif (length <= 18446744073709551615L): second_byte += 127 extra = struct.pack('!Q', length) else: raise FrameTooLargeException if mask: second_byte |= cls.MASK_MASK result.append(first_byte) result.append(second_byte) result.extend(extra) if mask: result.extend(mask) return result
'Called when a websocket has been created successfully.'
def run_websocket(self):
if getattr(self, 'prevent_wsgi_call', False): return if (not hasattr(self.server, 'clients')): self.server.clients = {} try: self.server.clients[self.client_address] = Client(self.client_address, self.websocket) list(self.application(self.environ, (lambda s, h, e=None: []))) finally: del self.server.clients[self.client_address] if (not self.websocket.closed): self.websocket.close() self.environ.update({'wsgi.websocket': None}) self.websocket = None
'Attempt to upgrade the current environ into a websocket enabled connection. If successful, the environ dict with be updated with two new entries, `wsgi.websocket` and `wsgi.websocket_version`. :returns: Whether the upgrade was successful.'
def upgrade_websocket(self):
self.logger.debug('Validating WebSocket request') if (self.environ.get('REQUEST_METHOD', '') != 'GET'): self.logger.debug('Can only upgrade connection if using GET method.') return upgrade = self.environ.get('HTTP_UPGRADE', '').lower() if (upgrade == 'websocket'): connection = self.environ.get('HTTP_CONNECTION', '').lower() if ('upgrade' not in connection): self.logger.warning("Client didn't ask for a connection upgrade") return else: return if (self.request_version != 'HTTP/1.1'): self.start_response('402 Bad Request', []) self.logger.warning('Bad server protocol in headers') return ['Bad protocol version'] if self.environ.get('HTTP_SEC_WEBSOCKET_VERSION'): return self.upgrade_connection() else: self.logger.warning('No protocol defined') self.start_response('426 Upgrade Required', [('Sec-WebSocket-Version', ', '.join(self.SUPPORTED_VERSIONS))]) return ['No Websocket protocol version defined']
'Validate and \'upgrade\' the HTTP request to a WebSocket request. If an upgrade succeeded then then handler will have `start_response` with a status of `101`, the environ will also be updated with `wsgi.websocket` and `wsgi.websocket_version` keys. :param environ: The WSGI environ dict. :param start_response: The callable used to start the response. :param stream: File like object that will be read from/written to by the underlying WebSocket object, if created. :return: The WSGI response iterator is something went awry.'
def upgrade_connection(self):
self.logger.debug('Attempting to upgrade connection') version = self.environ.get('HTTP_SEC_WEBSOCKET_VERSION') if (version not in self.SUPPORTED_VERSIONS): msg = 'Unsupported WebSocket Version: {0}'.format(version) self.logger.warning(msg) self.start_response('400 Bad Request', [('Sec-WebSocket-Version', ', '.join(self.SUPPORTED_VERSIONS))]) return [msg] key = self.environ.get('HTTP_SEC_WEBSOCKET_KEY', '').strip() if (not key): msg = 'Sec-WebSocket-Key header is missing/empty' self.logger.warning(msg) self.start_response('400 Bad Request', []) return [msg] try: key_len = len(base64.b64decode(key)) except TypeError: msg = 'Invalid key: {0}'.format(key) self.logger.warning(msg) self.start_response('400 Bad Request', []) return [msg] if (key_len != 16): msg = 'Invalid key: {0}'.format(key) self.logger.warning(msg) self.start_response('400 Bad Request', []) return [msg] requested_protocols = self.environ.get('HTTP_SEC_WEBSOCKET_PROTOCOL', '') protocol = None if hasattr(self.application, 'app_protocol'): allowed_protocol = self.application.app_protocol(self.environ['PATH_INFO']) if (allowed_protocol and (allowed_protocol in requested_protocols)): protocol = allowed_protocol self.logger.debug('Protocol allowed: {0}'.format(protocol)) self.websocket = WebSocket(self.environ, Stream(self), self) self.environ.update({'wsgi.websocket_version': version, 'wsgi.websocket': self.websocket}) if PY3: accept = base64.b64encode(hashlib.sha1((key + self.GUID).encode('latin-1')).digest()).decode('latin-1') else: accept = base64.b64encode(hashlib.sha1((key + self.GUID)).digest()) headers = [('Upgrade', 'websocket'), ('Connection', 'Upgrade'), ('Sec-WebSocket-Accept', accept)] if protocol: headers.append(('Sec-WebSocket-Protocol', protocol)) self.logger.debug('WebSocket request accepted, switching protocols') self.start_response('101 Switching Protocols', headers)
'Called when the handler is ready to send a response back to the remote endpoint. A websocket connection may have not been created.'
def start_response(self, status, headers, exc_info=None):
writer = super(WebSocketHandler, self).start_response(status, headers, exc_info=exc_info) self._prepare_response() return writer
'Sets up the ``pywsgi.Handler`` to work with a websocket response. This is used by other projects that need to support WebSocket connections as part of a larger effort.'
def _prepare_response(self):
assert (not self.headers_sent) if (not self.environ.get('wsgi.websocket')): return self.provided_content_length = False self.response_use_chunked = False self.close_connection = True self.provided_date = True
'I haven\'t seen this action type be sent from a tracker, but I\'ve left it here for the possibility.'
def _process_error(self, payload, trans):
self.error(payload) return payload
'http://www.bittorrent.org/beps/bep_0020.html'
def _generate_peer_id(self):
peer_id = (('-PU' + __version__.replace('.', '-')) + '-') remaining = (20 - len(peer_id)) numbers = [str(random.randint(0, 9)) for _ in xrange(remaining)] peer_id += ''.join(numbers) assert (len(peer_id) == 20) return peer_id
'update(arg)'
def update(self, arg):
RMD160Update(self.ctx, arg, len(arg)) self.dig = None
'digest()'
def digest(self):
if self.dig: return self.dig ctx = self.ctx.copy() self.dig = RMD160Final(self.ctx) self.ctx = ctx return self.dig
'hexdigest()'
def hexdigest(self):
dig = self.digest() hex_digest = '' for d in dig: if is_python2: hex_digest += ('%02x' % ord(d)) else: hex_digest += ('%02x' % d) return hex_digest
'copy()'
def copy(self):
import copy return copy.deepcopy(self)
'Batch RPC call. Pass array of arrays: [ [ "method", params... ], ... ] Returns array of results.'
def batch_(self, rpc_calls):
batch_data = [] for rpc_call in rpc_calls: AuthServiceProxy.__id_count += 1 m = rpc_call.pop(0) batch_data.append({'jsonrpc': '2.0', 'method': m, 'params': rpc_call, 'id': AuthServiceProxy.__id_count}) postdata = json.dumps(batch_data, default=EncodeDecimal) log.debug(('--> ' + postdata)) self.__conn.request('POST', self.__url.path, postdata, {'Host': self.__url.hostname, 'User-Agent': USER_AGENT, 'Authorization': self.__auth_header, 'Content-type': 'application/json'}) results = [] responses = self._get_response() for response in responses: if (response['error'] is not None): raise JSONRPCException(response['error']) elif ('result' not in response): raise JSONRPCException({'code': (-343), 'message': 'missing JSON-RPC result'}) else: results.append(response['result']) return results
'Return the longhand version of the IP address as a string.'
@property def exploded(self):
return self._explode_shorthand_ip_string()
'Return the shorthand version of the IP address as a string.'
@property def compressed(self):
return str(self)
'Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn\'t return the network or broadcast addresses.'
def iterhosts(self):
cur = (int(self.network) + 1) bcast = (int(self.broadcast) - 1) while (cur <= bcast): cur += 1 (yield IPAddress((cur - 1), version=self._version))
'Tell if self is partly contained in other.'
def overlaps(self, other):
return ((self.network in other) or (self.broadcast in other) or ((other.network in self) or (other.broadcast in self)))
'Number of hosts in the current subnet.'
@property def numhosts(self):
return ((int(self.broadcast) - int(self.network)) + 1)
'Remove an address from a larger block. For example: addr1 = IPNetwork(\'10.1.1.0/24\') addr2 = IPNetwork(\'10.1.1.0/26\') addr1.address_exclude(addr2) = [IPNetwork(\'10.1.1.64/26\'), IPNetwork(\'10.1.1.128/25\')] or IPv6: addr1 = IPNetwork(\'::1/32\') addr2 = IPNetwork(\'::1/128\') addr1.address_exclude(addr2) = [IPNetwork(\'::0/128\'), IPNetwork(\'::2/127\'), IPNetwork(\'::4/126\'), IPNetwork(\'::8/125\'), IPNetwork(\'0:0:8000::/33\')] Args: other: An IPvXNetwork object of the same type. Returns: A sorted list of IPvXNetwork objects addresses which is self minus other. Raises: TypeError: If self and other are of difffering address versions, or if other is not a network object. ValueError: If other is not completely contained by self.'
def address_exclude(self, other):
if (not (self._version == other._version)): raise TypeError(('%s and %s are not of the same version' % (str(self), str(other)))) if (not isinstance(other, _BaseNet)): raise TypeError(('%s is not a network object' % str(other))) if (other not in self): raise ValueError(('%s not contained in %s' % (str(other), str(self)))) if (other == self): return [] ret_addrs = [] other = IPNetwork(('%s/%s' % (str(other.network), str(other.prefixlen))), version=other._version) (s1, s2) = self.subnet() while ((s1 != other) and (s2 != other)): if (other in s1): ret_addrs.append(s2) (s1, s2) = s1.subnet() elif (other in s2): ret_addrs.append(s1) (s1, s2) = s2.subnet() else: assert (True == False), ('Error performing exclusion: s1: %s s2: %s other: %s' % (str(s1), str(s2), str(other))) if (s1 == other): ret_addrs.append(s2) elif (s2 == other): ret_addrs.append(s1) else: assert (True == False), ('Error performing exclusion: s1: %s s2: %s other: %s' % (str(s1), str(s2), str(other))) return sorted(ret_addrs, key=_BaseNet._get_networks_key)
'Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren\'t considered at all in this method. If you want to compare host bits, you can easily enough do a \'HostA._ip < HostB._ip\' Args: other: An IP object. Returns: If the IP versions of self and other are the same, returns: -1 if self < other: eg: IPv4(\'1.1.1.0/24\') < IPv4(\'1.1.2.0/24\') IPv6(\'1080::200C:417A\') < IPv6(\'1080::200B:417B\') 0 if self == other eg: IPv4(\'1.1.1.1/24\') == IPv4(\'1.1.1.2/24\') IPv6(\'1080::200C:417A/96\') == IPv6(\'1080::200C:417B/96\') 1 if self > other eg: IPv4(\'1.1.1.0/24\') > IPv4(\'1.1.0.0/24\') IPv6(\'1080::1:200C:417A/112\') > IPv6(\'1080::0:200C:417A/112\') If the IP versions of self and other are different, returns: -1 if self._version < other._version eg: IPv4(\'10.0.0.1/24\') < IPv6(\'::1/128\') 1 if self._version > other._version eg: IPv6(\'::1/128\') > IPv4(\'255.255.255.0/24\')'
def compare_networks(self, other):
if (self._version < other._version): return (-1) if (self._version > other._version): return 1 if (self.network < other.network): return (-1) if (self.network > other.network): return 1 if (self.netmask < other.netmask): return (-1) if (self.netmask > other.netmask): return 1 return 0
'Network-only key function. Returns an object that identifies this address\' network and netmask. This function is a suitable "key" argument for sorted() and list.sort().'
def _get_networks_key(self):
return (self._version, self.network, self.netmask)
'Turn the prefix length netmask into a int for comparison. Args: prefixlen: An integer, the prefix length. Returns: An integer.'
def _ip_int_from_prefix(self, prefixlen=None):
if ((not prefixlen) and (prefixlen != 0)): prefixlen = self._prefixlen return (self._ALL_ONES ^ (self._ALL_ONES >> prefixlen))
'Return prefix length from the decimal netmask. Args: ip_int: An integer, the IP address. mask: The netmask. Defaults to 32. Returns: An integer, the prefix length.'
def _prefix_from_ip_int(self, ip_int, mask=32):
while mask: if ((ip_int & 1) == 1): break ip_int >>= 1 mask -= 1 return mask
'Turn a prefix length into a dotted decimal string. Args: prefixlen: An integer, the netmask prefix length. Returns: A string, the dotted decimal netmask string.'
def _ip_string_from_prefix(self, prefixlen=None):
if (not prefixlen): prefixlen = self._prefixlen return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))
'The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), return a list with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_prefix is also set. new_prefix: The desired new prefix length. This must be a larger number (smaller prefix) than the existing prefix. This should not be set if prefixlen_diff is also set. Returns: An iterator of IPv(4|6) objects. Raises: ValueError: The prefixlen_diff is too small or too large. OR prefixlen_diff and new_prefix are both set or new_prefix is a smaller number than the current prefix (smaller number means a larger network)'
def iter_subnets(self, prefixlen_diff=1, new_prefix=None):
if (self._prefixlen == self._max_prefixlen): (yield self) return if (new_prefix is not None): if (new_prefix < self._prefixlen): raise ValueError('new prefix must be longer') if (prefixlen_diff != 1): raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = (new_prefix - self._prefixlen) if (prefixlen_diff < 0): raise ValueError('prefix length diff must be > 0') new_prefixlen = (self._prefixlen + prefixlen_diff) if (not self._is_valid_netmask(str(new_prefixlen))): raise ValueError(('prefix length diff %d is invalid for netblock %s' % (new_prefixlen, str(self)))) first = IPNetwork(('%s/%s' % (str(self.network), str((self._prefixlen + prefixlen_diff)))), version=self._version) (yield first) current = first while True: broadcast = current.broadcast if (broadcast == self.broadcast): return new_addr = IPAddress((int(broadcast) + 1), version=self._version) current = IPNetwork(('%s/%s' % (str(new_addr), str(new_prefixlen))), version=self._version) (yield current)
'Return the network object with the host bits masked out.'
def masked(self):
return IPNetwork(('%s/%d' % (self.network, self._prefixlen)), version=self._version)
'Return a list of subnets, rather than an iterator.'
def subnet(self, prefixlen_diff=1, new_prefix=None):
return list(self.iter_subnets(prefixlen_diff, new_prefix))
'The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a negative prefix length. OR If prefixlen_diff and new_prefix are both set or new_prefix is a larger number than the current prefix (larger number means a smaller network)'
def supernet(self, prefixlen_diff=1, new_prefix=None):
if (self._prefixlen == 0): return self if (new_prefix is not None): if (new_prefix > self._prefixlen): raise ValueError('new prefix must be shorter') if (prefixlen_diff != 1): raise ValueError('cannot set prefixlen_diff and new_prefix') prefixlen_diff = (self._prefixlen - new_prefix) if ((self.prefixlen - prefixlen_diff) < 0): raise ValueError(('current prefixlen is %d, cannot have a prefixlen_diff of %d' % (self.prefixlen, prefixlen_diff))) return IPNetwork(('%s/%s' % (str(self.network), str((self.prefixlen - prefixlen_diff)))), version=self._version)
'Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn\'t a valid IPv4 Address.'
def _ip_int_from_string(self, ip_str):
octets = ip_str.split('.') if (len(octets) != 4): raise AddressValueError(ip_str) packed_ip = 0 for oc in octets: try: packed_ip = ((packed_ip << 8) | self._parse_octet(oc)) except ValueError: raise AddressValueError(ip_str) return packed_ip
'Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn\'t strictly a decimal from [0..255].'
def _parse_octet(self, octet_str):
if (not self._DECIMAL_DIGITS.issuperset(octet_str)): raise ValueError octet_int = int(octet_str, 10) if ((octet_int > 255) or ((octet_str[0] == '0') and (len(octet_str) > 1))): raise ValueError return octet_int
'Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation.'
def _string_from_ip_int(self, ip_int):
octets = [] for _ in xrange(4): octets.insert(0, str((ip_int & 255))) ip_int >>= 8 return '.'.join(octets)
'The binary representation of this address.'
@property def packed(self):
return v4_int_to_packed(self._ip)
'Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range.'
@property def is_reserved(self):
return (self in IPv4Network('240.0.0.0/4'))
'Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per RFC 1918.'
@property def is_private(self):
return ((self in IPv4Network('10.0.0.0/8')) or (self in IPv4Network('172.16.0.0/12')) or (self in IPv4Network('192.168.0.0/16')))
'Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details.'
@property def is_multicast(self):
return (self in IPv4Network('224.0.0.0/4'))
'Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3.'
@property def is_unspecified(self):
return (self in IPv4Network('0.0.0.0'))
'Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330.'
@property def is_loopback(self):
return (self in IPv4Network('127.0.0.0/8'))
'Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927.'
@property def is_link_local(self):
return (self in IPv4Network('169.254.0.0/16'))