Ejemplo n.º 1
0
class CertStatus(univ.Choice):
    componentType = namedtype.NamedTypes(namedtype.NamedType('good', univ.Null().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), namedtype.NamedType('revoked', RevokedInfo().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))), namedtype.NamedType('unknown', UnknownInfo().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))))
Ejemplo n.º 2
0
class Null(OctetString):
    defaultValue = ''.encode()  # This is tightly constrained
    tagSet = baseTagSet = tag.initTagSet(
        tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x05))
    subtypeSpec = OctetString.subtypeSpec + constraint.SingleValueConstraint(
        ''.encode())
Ejemplo n.º 3
0
class Real(base.AbstractSimpleAsn1Item):
    try:
        _plusInf = float('inf')
        _minusInf = float('-inf')
        _inf = (_plusInf, _minusInf)
    except ValueError:
        # Infinity support is platform and Python dependent
        _plusInf = _minusInf = None
        _inf = ()

    tagSet = baseTagSet = tag.initTagSet(
        tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x09))

    def __normalizeBase10(self, value):
        m, b, e = value
        while m and m % 10 == 0:
            m = m / 10
            e = e + 1
        return m, b, e

    def prettyIn(self, value):
        if isinstance(value, tuple) and len(value) == 3:
            for d in value:
                if not isinstance(d, intTypes):
                    raise error.PyAsn1Error('Lame Real value syntax: %s' %
                                            (value, ))
            if value[1] not in (2, 10):
                raise error.PyAsn1Error('Prohibited base for Real value: %s' %
                                        (value[1], ))
            if value[1] == 10:
                value = self.__normalizeBase10(value)
            return value
        elif isinstance(value, intTypes):
            return self.__normalizeBase10((value, 10, 0))
        elif isinstance(value, float):
            if self._inf and value in self._inf:
                return value
            else:
                e = 0
                while int(value) != value:
                    value = value * 10
                    e = e - 1
                return self.__normalizeBase10((int(value), 10, e))
        elif isinstance(value, Real):
            return tuple(value)
        elif isinstance(value, str):  # handle infinite literal
            try:
                return float(value)
            except ValueError:
                pass
        raise error.PyAsn1Error('Bad real value syntax: %s' % (value, ))

    def prettyOut(self, value):
        if value in self._inf:
            return '\'%s\'' % value
        else:
            return str(value)

    def isPlusInfinity(self):
        return self._value == self._plusInf

    def isMinusInfinity(self):
        return self._value == self._minusInf

    def isInfinity(self):
        return self._value in self._inf

    def __str__(self):
        return str(float(self))

    def __add__(self, value):
        return self.clone(float(self) + value)

    def __radd__(self, value):
        return self + value

    def __mul__(self, value):
        return self.clone(float(self) * value)

    def __rmul__(self, value):
        return self * value

    def __sub__(self, value):
        return self.clone(float(self) - value)

    def __rsub__(self, value):
        return self.clone(value - float(self))

    def __mod__(self, value):
        return self.clone(float(self) % value)

    def __rmod__(self, value):
        return self.clone(value % float(self))

    def __pow__(self, value, modulo=None):
        return self.clone(pow(float(self), value, modulo))

    def __rpow__(self, value):
        return self.clone(pow(value, float(self)))

    if sys.version_info[0] <= 2:

        def __div__(self, value):
            return self.clone(float(self) / value)

        def __rdiv__(self, value):
            return self.clone(value / float(self))
    else:

        def __truediv__(self, value):
            return self.clone(float(self) / value)

        def __rtruediv__(self, value):
            return self.clone(value / float(self))

        def __divmod__(self, value):
            return self.clone(float(self) // value)

        def __rdivmod__(self, value):
            return self.clone(value // float(self))

    def __int__(self):
        return int(float(self))

    if sys.version_info[0] <= 2:

        def __long__(self):
            return int(float(self))

    def __float__(self):
        if self._value in self._inf:
            return self._value
        else:
            return float(self._value[0] * pow(self._value[1], self._value[2]))

    def __abs__(self):
        return abs(float(self))

    def __lt__(self, value):
        return float(self) < value

    def __le__(self, value):
        return float(self) <= value

    def __eq__(self, value):
        return float(self) == value

    def __ne__(self, value):
        return float(self) != value

    def __gt__(self, value):
        return float(self) > value

    def __ge__(self, value):
        return float(self) >= value

    if sys.version_info[0] <= 2:

        def __nonzero__(self):
            return bool(float(self))
    else:

        def __bool__(self):
            return bool(float(self))

        __hash__ = base.AbstractSimpleAsn1Item.__hash__

    def __getitem__(self, idx):
        if self._value in self._inf:
            raise error.PyAsn1Error('Invalid infinite value operation')
        else:
            return self._value[idx]
Ejemplo n.º 4
0
class Integer(base.AbstractSimpleAsn1Item):
    tagSet = baseTagSet = tag.initTagSet(
        tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x02))
    namedValues = namedval.NamedValues()

    def __init__(self,
                 value=None,
                 tagSet=None,
                 subtypeSpec=None,
                 namedValues=None):
        if namedValues is None:
            self.__namedValues = self.namedValues
        else:
            self.__namedValues = namedValues
        base.AbstractSimpleAsn1Item.__init__(self, value, tagSet, subtypeSpec)

    def __and__(self, value):
        return self.clone(self._value & value)

    def __rand__(self, value):
        return self.clone(value & self._value)

    def __or__(self, value):
        return self.clone(self._value | value)

    def __ror__(self, value):
        return self.clone(value | self._value)

    def __xor__(self, value):
        return self.clone(self._value ^ value)

    def __rxor__(self, value):
        return self.clone(value ^ self._value)

    def __lshift__(self, value):
        return self.clone(self._value << value)

    def __rshift__(self, value):
        return self.clone(self._value >> value)

    def __add__(self, value):
        return self.clone(self._value + value)

    def __radd__(self, value):
        return self.clone(value + self._value)

    def __sub__(self, value):
        return self.clone(self._value - value)

    def __rsub__(self, value):
        return self.clone(value - self._value)

    def __mul__(self, value):
        return self.clone(self._value * value)

    def __rmul__(self, value):
        return self.clone(value * self._value)

    def __mod__(self, value):
        return self.clone(self._value % value)

    def __rmod__(self, value):
        return self.clone(value % self._value)

    def __pow__(self, value, modulo=None):
        return self.clone(pow(self._value, value, modulo))

    def __rpow__(self, value):
        return self.clone(pow(value, self._value))

    if sys.version_info[0] <= 2:

        def __div__(self, value):
            return self.clone(self._value // value)

        def __rdiv__(self, value):
            return self.clone(value // self._value)
    else:

        def __truediv__(self, value):
            return self.clone(self._value / value)

        def __rtruediv__(self, value):
            return self.clone(value / self._value)

        def __divmod__(self, value):
            return self.clone(self._value // value)

        def __rdivmod__(self, value):
            return self.clone(value // self._value)

        __hash__ = base.AbstractSimpleAsn1Item.__hash__

    def __int__(self):
        return int(self._value)

    if sys.version_info[0] <= 2:

        def __long__(self):
            return int(self._value)

    def __float__(self):
        return float(self._value)

    def __abs__(self):
        return abs(self._value)

    def __index__(self):
        return int(self._value)

    def __lt__(self, value):
        return self._value < value

    def __le__(self, value):
        return self._value <= value

    def __eq__(self, value):
        return self._value == value

    def __ne__(self, value):
        return self._value != value

    def __gt__(self, value):
        return self._value > value

    def __ge__(self, value):
        return self._value >= value

    def prettyIn(self, value):
        if not isinstance(value, str):
            return int(value)
        r = self.__namedValues.getValue(value)
        if r is not None:
            return r
        try:
            return int(value)
        except ValueError:
            raise error.PyAsn1Error('Can\'t coerce %s into integer: %s' %
                                    (value, sys.exc_info()[1]))

    def prettyOut(self, value):
        r = self.__namedValues.getName(value)
        return r is None and str(value) or repr(r)

    def getNamedValues(self):
        return self.__namedValues

    def clone(self,
              value=None,
              tagSet=None,
              subtypeSpec=None,
              namedValues=None):
        if value is None and tagSet is None and subtypeSpec is None \
               and namedValues is None:
            return self
        if value is None:
            value = self._value
        if tagSet is None:
            tagSet = self._tagSet
        if subtypeSpec is None:
            subtypeSpec = self._subtypeSpec
        if namedValues is None:
            namedValues = self.__namedValues
        return self.__class__(value, tagSet, subtypeSpec, namedValues)

    def subtype(self,
                value=None,
                implicitTag=None,
                explicitTag=None,
                subtypeSpec=None,
                namedValues=None):
        if value is None:
            value = self._value
        if implicitTag is not None:
            tagSet = self._tagSet.tagImplicitly(implicitTag)
        elif explicitTag is not None:
            tagSet = self._tagSet.tagExplicitly(explicitTag)
        else:
            tagSet = self._tagSet
        if subtypeSpec is None:
            subtypeSpec = self._subtypeSpec
        else:
            subtypeSpec = subtypeSpec + self._subtypeSpec
        if namedValues is None:
            namedValues = self.__namedValues
        else:
            namedValues = namedValues + self.__namedValues
        return self.__class__(value, tagSet, subtypeSpec, namedValues)
Ejemplo n.º 5
0
class BitString(base.AbstractSimpleAsn1Item):
    tagSet = baseTagSet = tag.initTagSet(
        tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x03))
    namedValues = namedval.NamedValues()

    def __init__(self,
                 value=None,
                 tagSet=None,
                 subtypeSpec=None,
                 namedValues=None):
        if namedValues is None:
            self.__namedValues = self.namedValues
        else:
            self.__namedValues = namedValues
        base.AbstractSimpleAsn1Item.__init__(self, value, tagSet, subtypeSpec)

    def clone(self,
              value=None,
              tagSet=None,
              subtypeSpec=None,
              namedValues=None):
        if value is None and tagSet is None and subtypeSpec is None \
               and namedValues is None:
            return self
        if value is None:
            value = self._value
        if tagSet is None:
            tagSet = self._tagSet
        if subtypeSpec is None:
            subtypeSpec = self._subtypeSpec
        if namedValues is None:
            namedValues = self.__namedValues
        return self.__class__(value, tagSet, subtypeSpec, namedValues)

    def subtype(self,
                value=None,
                implicitTag=None,
                explicitTag=None,
                subtypeSpec=None,
                namedValues=None):
        if value is None:
            value = self._value
        if implicitTag is not None:
            tagSet = self._tagSet.tagImplicitly(implicitTag)
        elif explicitTag is not None:
            tagSet = self._tagSet.tagExplicitly(explicitTag)
        else:
            tagSet = self._tagSet
        if subtypeSpec is None:
            subtypeSpec = self._subtypeSpec
        else:
            subtypeSpec = subtypeSpec + self._subtypeSpec
        if namedValues is None:
            namedValues = self.__namedValues
        else:
            namedValues = namedValues + self.__namedValues
        return self.__class__(value, tagSet, subtypeSpec, namedValues)

    def __str__(self):
        return str(tuple(self))

    # Immutable sequence object protocol

    def __len__(self):
        if self._len is None:
            self._len = len(self._value)
        return self._len

    def __getitem__(self, i):
        if isinstance(i, slice):
            return self.clone(operator.getitem(self._value, i))
        else:
            return self._value[i]

    def __add__(self, value):
        return self.clone(self._value + value)

    def __radd__(self, value):
        return self.clone(value + self._value)

    def __mul__(self, value):
        return self.clone(self._value * value)

    def __rmul__(self, value):
        return self * value

    def prettyIn(self, value):
        r = []
        if not value:
            return ()
        elif isinstance(value, str):
            if value[0] == '\'':
                if value[-2:] == '\'B':
                    for v in value[1:-2]:
                        if v == '0':
                            r.append(0)
                        elif v == '1':
                            r.append(1)
                        else:
                            raise error.PyAsn1Error(
                                'Non-binary BIT STRING initializer %s' % (v, ))
                    return tuple(r)
                elif value[-2:] == '\'H':
                    for v in value[1:-2]:
                        i = 4
                        v = int(v, 16)
                        while i:
                            i = i - 1
                            r.append((v >> i) & 0x01)
                    return tuple(r)
                else:
                    raise error.PyAsn1Error(
                        'Bad BIT STRING value notation %s' % (value, ))
            else:
                for i in value.split(','):
                    j = self.__namedValues.getValue(i)
                    if j is None:
                        raise error.PyAsn1Error(
                            'Unknown bit identifier \'%s\'' % (i, ))
                    if j >= len(r):
                        r.extend([0] * (j - len(r) + 1))
                    r[j] = 1
                return tuple(r)
        elif isinstance(value, (tuple, list)):
            r = tuple(value)
            for b in r:
                if b and b != 1:
                    raise error.PyAsn1Error(
                        'Non-binary BitString initializer \'%s\'' % (r, ))
            return r
        elif isinstance(value, BitString):
            return tuple(value)
        else:
            raise error.PyAsn1Error('Bad BitString initializer type \'%s\'' %
                                    (value, ))

    def prettyOut(self, value):
        return '\"\'%s\'B\"' % ''.join([str(x) for x in value])
Ejemplo n.º 6
0
class Counter64(univ.Integer):
    tagSet = univ.Integer.tagSet.tagImplicitly(
        tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x06))
    subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint(
        0, 18446744073709551615)
Ejemplo n.º 7
0

ASIdentifierChoice.componentType = namedtype.NamedTypes(
    namedtype.NamedType('inherit', univ.Null()),
    namedtype.NamedType('asIdsOrRanges',
                        univ.SequenceOf(componentType=ASIdOrRange())))


class ASIdentifiers(univ.Sequence):
    pass


ASIdentifiers.componentType = namedtype.NamedTypes(
    namedtype.OptionalNamedType(
        'asnum',
        ASIdentifierChoice().subtype(explicitTag=tag.Tag(
            tag.tagClassContext, tag.tagFormatConstructed, 0))),
    namedtype.OptionalNamedType(
        'rdi',
        ASIdentifierChoice().subtype(explicitTag=tag.Tag(
            tag.tagClassContext, tag.tagFormatConstructed, 1))))

# Update the Certificate Extensions Map

_certificateExtensionsMapUpdate = {
    id_pe_ipAddrBlocks: IPAddrBlocks(),
    id_pe_autonomousSysIds: ASIdentifiers(),
}

certificateExtensionsMap.update(_certificateExtensionsMapUpdate)
Ejemplo n.º 8
0
class Signature(univ.Sequence):
    componentType = namedtype.NamedTypes(namedtype.NamedType('signatureAlgorithm', rfc2459.AlgorithmIdentifier()), namedtype.NamedType('signature', univ.BitString()), namedtype.OptionalNamedType('certs', univ.SequenceOf(rfc2459.Certificate()).subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))))
Ejemplo n.º 9
0
class TBSRequest(univ.Sequence):
    componentType = namedtype.NamedTypes(namedtype.DefaultedNamedType('version', Version('v1').subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), namedtype.OptionalNamedType('requestorName', GeneralName().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))), namedtype.NamedType('requestList', univ.SequenceOf(Request())), namedtype.OptionalNamedType('requestExtensions', rfc2459.Extensions().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))))
Ejemplo n.º 10
0
class OCSPResponse(univ.Sequence):
    componentType = namedtype.NamedTypes(namedtype.NamedType('responseStatus', OCSPResponseStatus()), namedtype.OptionalNamedType('responseBytes', ResponseBytes().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))))
Ejemplo n.º 11
0
class Request(univ.Sequence):
    componentType = namedtype.NamedTypes(namedtype.NamedType('reqCert', CertID()), namedtype.OptionalNamedType('singleRequestExtensions', rfc2459.Extensions().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))))
Ejemplo n.º 12
0
class ResponseData(univ.Sequence):
    componentType = namedtype.NamedTypes(namedtype.DefaultedNamedType('version', Version('v1').subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), namedtype.NamedType('responderID', ResponderID()), namedtype.NamedType('producedAt', useful.GeneralizedTime()), namedtype.NamedType('responses', univ.SequenceOf(SingleResponse())), namedtype.OptionalNamedType('responseExtensions', rfc2459.Extensions().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))))
Ejemplo n.º 13
0
class ResponderID(univ.Choice):
    componentType = namedtype.NamedTypes(namedtype.NamedType('byName', rfc2459.Name().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))), namedtype.NamedType('byKey', KeyHash().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))))
Ejemplo n.º 14
0
class SingleResponse(univ.Sequence):
    componentType = namedtype.NamedTypes(namedtype.NamedType('certID', CertID()), namedtype.NamedType('certStatus', CertStatus()), namedtype.NamedType('thisUpdate', useful.GeneralizedTime()), namedtype.OptionalNamedType('nextUpdate', useful.GeneralizedTime().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), namedtype.OptionalNamedType('singleExtensions', rfc2459.Extensions().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))))
Ejemplo n.º 15
0
class TimeTicks(univ.Integer):
    tagSet = univ.Integer.tagSet.tagImplicitly(
        tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x03))
    subtypeSpec = univ.Integer.subtypeSpec + constraint.ValueRangeConstraint(
        0, 4294967295)
Ejemplo n.º 16
0
class OCSPRequest(univ.Sequence):
    componentType = namedtype.NamedTypes(namedtype.NamedType('tbsRequest', TBSRequest()), namedtype.OptionalNamedType('optionalSignature', Signature().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))))
Ejemplo n.º 17
0
class Opaque(univ.OctetString):
    tagSet = univ.OctetString.tagSet.tagImplicitly(
        tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x04))
Ejemplo n.º 18
0
        'certificationRequestInfo', univ.Sequence(
            componentType=namedtype.NamedTypes(
                namedtype.NamedType('version', univ.Integer()),
                namedtype.NamedType('subject', rfc5280.Name()),
                namedtype.NamedType(
                    'subjectPublicKeyInfo', univ.Sequence(
                        componentType=namedtype.NamedTypes(
                            namedtype.NamedType('algorithm', rfc5280.AlgorithmIdentifier()),
                            namedtype.NamedType('subjectPublicKey', univ.BitString())
                        )
                    )
                ),
                namedtype.NamedType(
                    'attributes', univ.SetOf(
                        componentType=rfc5652.Attribute()).subtype(
                        implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))
                )
            )
        )
    ),
    namedtype.NamedType('signatureAlgorithm', rfc5280.AlgorithmIdentifier()),
    namedtype.NamedType('signature', univ.BitString())
)


class TaggedCertificationRequest(univ.Sequence):
    pass


TaggedCertificationRequest.componentType = namedtype.NamedTypes(
    namedtype.NamedType('bodyPartID', BodyPartID()),
Ejemplo n.º 19
0
def convert_signatures_to_asn(pydict_signatures):
    """
  Given a Python dictionary compliant with tuf.formats.SIGNATURES_SCHEMA,
  containing signatures, convert it to an ASN.1 (pyasn1) representation
  that conforms to the uptane.encoding.asn1_definitions.Signatures() class.

  The data contained (the signature values, keyids, and method) are not changed.

  This is the exact reverse of convert_signatures_to_json(); providing the
  output of this function as input to that function should reproduce the initial
  input to this function. Also vice versa.
  """

    # Create a pyASN.1 object of custom class Signatures, containing some
    # unknown pyasn1 sorcery to specify types.
    # Because this Signatures() object is going to be a member of the Metadata()
    # object below, subtype() must be called on it to make its tags match the tags
    # expected by the parent object that must contain it.
    # The following documents tagging in pyasn1:
    #   http://www.red-bean.com/doc/python-pyasn1/pyasn1-tutorial.html#1.2
    asn_signatures_list = asn1_spec.Signatures().subtype(
        implicitTag=p_type_tag.Tag(p_type_tag.tagClassContext,
                                   p_type_tag.tagFormatSimple, 2))

    # Now convert each Python dictionary-style signature into an ASN.1 signature
    # and stick those into the ASN.1 list just created.
    # Note that a Signatures() object has no append() method, so we clumsily
    # iterate through with index 'i'.
    i = 0  # Index for iterating through asn
    for pydict_sig in pydict_signatures:

        # Construct an ASN.1 representation of the signature and populate it.
        asn_sig = asn1_spec.Signature()

        # This hideous stuff constructs a Keyid() object and assigns it the
        # value from pydict_sig['keyid'] through pyasn1. I'm sure that some
        # methods added to the class could ameliorate this. Since the class is code
        # generated by pyasn1 from an asn1 definition, the way to do this might be
        # to use a class that inherits from that auto-generated class... but that's
        # quite confusing to a reader, too.
        # asn_sig['keyid'] = pydict_sig['keyid'] # <- used to just be this
        asn_sig['keyid'] = asn1_spec.Keyid().subtype(
            explicitTag=p_type_tag.Tag(p_type_tag.tagClassContext,
                                       p_type_tag.tagFormatConstructed, 0))
        asn_sig['keyid']['octetString'] = p_type_univ.OctetString(
            hexValue=pydict_sig['keyid']).subtype(implicitTag=p_type_tag.Tag(
                p_type_tag.tagClassContext, p_type_tag.tagFormatSimple, 1))

        # Because 'method' is an enum, extracting the string value is a bit messy.
        asn_sig['method'] = int(asn1_spec.SignatureMethod(
            pydict_sig['method']))

        # This hideous stuff constructs a BinaryData() object to hold the actual
        # signature itself, and assigns it the value from pydict_sig['sig'] through
        # pyasn1. I'm sure that some methods added to the class could ameliorate
        # this. Since the class is code generated by pyasn1 from an asn1 definition,
        # the way to do this might be to use a class that inherits from that
        # auto-generated class... but that's quite confusing to a reader, too.
        #asn_sig['value'] = pydict_sig['sig'] # <- used to just be this
        asn_sig['value'] = asn1_spec.BinaryData().subtype(
            explicitTag=p_type_tag.Tag(p_type_tag.tagClassContext,
                                       p_type_tag.tagFormatConstructed, 2))
        asn_sig['value']['octetString'] = p_type_univ.OctetString(
            hexValue=pydict_sig['sig']).subtype(implicitTag=p_type_tag.Tag(
                p_type_tag.tagClassContext, p_type_tag.tagFormatSimple, 1))

        # Add to the Signatures() list.
        asn_signatures_list[i] = asn_sig  # has no append method
        i += 1

    return asn_signatures_list
Ejemplo n.º 20
0

OtherRevocationInfoFormat.componentType = namedtype.NamedTypes(
    namedtype.NamedType('otherRevInfoFormat', univ.ObjectIdentifier()),
    namedtype.NamedType('otherRevInfo', univ.Any()))


class RevocationInfoChoice(univ.Choice):
    pass


RevocationInfoChoice.componentType = namedtype.NamedTypes(
    namedtype.NamedType('crl', rfc3280.CertificateList()),
    namedtype.NamedType(
        'other',
        OtherRevocationInfoFormat().subtype(implicitTag=tag.Tag(
            tag.tagClassContext, tag.tagFormatConstructed, 1))))


class RevocationInfoChoices(univ.SetOf):
    pass


RevocationInfoChoices.componentType = RevocationInfoChoice()


class OtherKeyAttribute(univ.Sequence):
    pass


OtherKeyAttribute.componentType = namedtype.NamedTypes(
    namedtype.NamedType('keyAttrId', univ.ObjectIdentifier()),
    pass


JWTClaimPermittedValuesList.componentType = JWTClaimPermittedValues()
JWTClaimPermittedValuesList.sizeSpec = constraint.ValueSizeConstraint(1, MAX)


class JWTClaimConstraints(univ.Sequence):
    pass


JWTClaimConstraints.componentType = namedtype.NamedTypes(
    namedtype.OptionalNamedType(
        'mustInclude',
        JWTClaimNames().subtype(
            explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))),
    namedtype.OptionalNamedType(
        'permittedValues',
        JWTClaimPermittedValuesList().subtype(
            explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))))

JWTClaimConstraints.sizeSpec = univ.Sequence.sizeSpec + constraint.ValueSizeConstraint(
    1, 2)

id_pe_JWTClaimConstraints = _OID(1, 3, 6, 1, 5, 5, 7, 1, 27)


class ServiceProviderCode(char.IA5String):
    pass

Ejemplo n.º 22
0
    def timestamp_response(self):
        verified, failureInfo = self.verify()

        if not verified:
            return self.error_response(failureInfo)

        # TST Info
        tst_info = classes.TSTInfo()
        tst_info['version'] = 1
        tst_info['policy'] = constants.id_baseline_policy
        tst_info['messageImprint'] = self.timestamp_request.messageImprint
        tst_info['serialNumber'] = self.serial_number()

        try:
            time = self.gen_time()
        except:
            return self.error_response(
                classes.PKIFailureInfo("timeNotAvailable"))

        tst_info['genTime'] = time

        if self.timestamp_request.nonce != None:
            tst_info['nonce'] = self.timestamp_request.nonce

        # ContentInfo
        encodedContent = der_encoder.encode(tst_info)

        contentInfo = rfc3852.EncapsulatedContentInfo()
        contentInfo['eContentType'] = constants.id_ct_TSTInfo
        contentInfo['eContent'] = univ.OctetString().subtype(
            value=encodedContent,
            explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))

        # DigestAlgorithm
        algorithm_identifier = rfc3280.AlgorithmIdentifier()
        algorithm_identifier.setComponentByPosition(0, constants.id_sha256)
        algorithm_identifier.setComponentByPosition(1, univ.Null(''))

        digestAlgorithms = rfc3852.DigestAlgorithmIdentifiers()
        digestAlgorithms.setComponentByPosition(0, algorithm_identifier)

        # SignerInfo
        signerInfo = rfc3852.SignerInfo()
        signerInfo['version'] = 1  # rfc 3852

        issuer = rfc3852.IssuerAndSerialNumber()
        issuer['issuer'] = self.cert_issuer_name()
        issuer['serialNumber'] = rfc3280.CertificateSerialNumber(
            self.certificate.serial_number)

        sid = rfc3852.SignerIdentifier()
        sid['issuerAndSerialNumber'] = issuer
        signerInfo['sid'] = sid

        signerDigestAlgorithm = rfc3280.AlgorithmIdentifier()
        signerDigestAlgorithm.setComponentByPosition(0, constants.id_sha256)
        signerDigestAlgorithm.setComponentByPosition(1, univ.Null(''))
        signerInfo['digestAlgorithm'] = signerDigestAlgorithm

        signerEncryptionAlgorithm = rfc3280.AlgorithmIdentifier()
        signerEncryptionAlgorithm.setComponentByPosition(0, constants.id_rsa)
        signerEncryptionAlgorithm.setComponentByPosition(1, univ.Null(''))
        signerInfo['signatureAlgorithm'] = signerEncryptionAlgorithm

        # SignedAttributes
        attributes = rfc3852.SignedAttributes().subtype(
            implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))

        # Content Type
        attr_content_type = self.attr_content_type()
        attributes.setComponentByPosition(0, attr_content_type)

        # Message digest
        attr_message_digest = self.attr_message_digest(encodedContent)
        attributes.setComponentByPosition(1, attr_message_digest)

        # Signing Certificate
        attr_signing_certificate = self.attr_signing_certificate()
        attributes.setComponentByPosition(2, attr_signing_certificate)

        signerInfo['signedAttrs'] = attributes

        # Signature
        s = univ.SetOf()
        for i, x in enumerate(attributes):
            s.setComponentByPosition(i, x)
        signed_data = der_encoder.encode(s)

        signature = self.private_key.sign(signed_data, padding.PKCS1v15(),
                                          hashes.SHA256())
        signerInfo['signature'] = signature

        signerInfos = rfc3852.SignerInfos()
        signerInfos.setComponentByPosition(0, signerInfo)

        signedContent = rfc3852.SignedData().subtype(explicitTag=tag.Tag(
            tag.tagClassContext, tag.tagFormatConstructed, 0))
        signedContent['version'] = 3
        signedContent['digestAlgorithms'] = digestAlgorithms
        signedContent['encapContentInfo'] = contentInfo
        signedContent['signerInfos'] = signerInfos

        # Certificates
        if self.timestamp_request.certReq == True:
            certificate, substrate = der_decoder.decode(
                self.certificate.public_bytes(serialization.Encoding.DER),
                asn1Spec=rfc3280.Certificate())
            ext_certificate = rfc3852.CertificateChoices()
            ext_certificate['certificate'] = certificate

            certificates = rfc3852.CertificateSet().subtype(
                implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple,
                                    0))
            certificates.setComponentByPosition(0, ext_certificate)
            signedContent['certificates'] = certificates

        # Token
        token = classes.TimeStampToken()
        token['content'] = signedContent
        token['contentType'] = rfc3852.id_signedData

        # Status
        statusInfo = classes.PKIStatusInfo()
        statusInfo['status'] = classes.PKIStatus('granted')

        # Response
        response = classes.TimeStampResp()
        response['status'] = statusInfo
        response['timeStampToken'] = token

        return self.encode_timestamp_response(response)
Ejemplo n.º 23
0
class Boolean(Integer):
    tagSet = baseTagSet = tag.initTagSet(
        tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x01), )
    subtypeSpec = Integer.subtypeSpec + constraint.SingleValueConstraint(0, 1)
    namedValues = Integer.namedValues.clone(('False', 0), ('True', 1))
PKIFreeText = rfc4210.PKIFreeText

id_ct_TSTInfo = univ.ObjectIdentifier('1.2.840.113549.1.9.16.1.4')


class Accuracy(univ.Sequence):
    pass


Accuracy.componentType = namedtype.NamedTypes(
    namedtype.OptionalNamedType('seconds', univ.Integer()),
    namedtype.OptionalNamedType(
        'millis',
        univ.Integer().
        subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 999)).subtype(
            implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))),
    namedtype.OptionalNamedType(
        'micros',
        univ.Integer().
        subtype(subtypeSpec=constraint.ValueRangeConstraint(1, 999)).subtype(
            implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))))


class MessageImprint(univ.Sequence):
    pass


MessageImprint.componentType = namedtype.NamedTypes(
    namedtype.NamedType('hashAlgorithm', AlgorithmIdentifier()),
    namedtype.NamedType('hashedMessage', univ.OctetString()))
Ejemplo n.º 25
0
class OctetString(base.AbstractSimpleAsn1Item):
    tagSet = baseTagSet = tag.initTagSet(
        tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x04))
    defaultBinValue = defaultHexValue = base.noValue
    encoding = 'us-ascii'

    def __init__(self,
                 value=None,
                 tagSet=None,
                 subtypeSpec=None,
                 encoding=None,
                 binValue=None,
                 hexValue=None):
        if encoding is None:
            self._encoding = self.encoding
        else:
            self._encoding = encoding
        if binValue is not None:
            value = self.fromBinaryString(binValue)
        if hexValue is not None:
            value = self.fromHexString(hexValue)
        if value is None or value is base.noValue:
            value = self.defaultHexValue
        if value is None or value is base.noValue:
            value = self.defaultBinValue
        self.__intValue = None
        base.AbstractSimpleAsn1Item.__init__(self, value, tagSet, subtypeSpec)

    def clone(self,
              value=None,
              tagSet=None,
              subtypeSpec=None,
              encoding=None,
              binValue=None,
              hexValue=None):
        if value is None and tagSet is None and subtypeSpec is None and \
               encoding is None and binValue is None and hexValue is None:
            return self
        if value is None and binValue is None and hexValue is None:
            value = self._value
        if tagSet is None:
            tagSet = self._tagSet
        if subtypeSpec is None:
            subtypeSpec = self._subtypeSpec
        if encoding is None:
            encoding = self._encoding
        return self.__class__(value, tagSet, subtypeSpec, encoding, binValue,
                              hexValue)

    if sys.version_info[0] <= 2:

        def prettyIn(self, value):
            if isinstance(value, str):
                return value
            elif isinstance(value, (tuple, list)):
                try:
                    return ''.join([chr(x) for x in value])
                except ValueError:
                    raise error.PyAsn1Error(
                        'Bad OctetString initializer \'%s\'' % (value, ))
            else:
                return str(value)
    else:

        def prettyIn(self, value):
            if isinstance(value, bytes):
                return value
            elif isinstance(value, OctetString):
                return value.asOctets()
            elif isinstance(value, (tuple, list, map)):
                try:
                    return bytes(value)
                except ValueError:
                    raise error.PyAsn1Error(
                        'Bad OctetString initializer \'%s\'' % (value, ))
            else:
                try:
                    return str(value).encode(self._encoding)
                except UnicodeEncodeError:
                    raise error.PyAsn1Error(
                        'Can\'t encode string \'%s\' with \'%s\' codec' %
                        (value, self._encoding))

    def fromBinaryString(self, value):
        bitNo = 8
        byte = 0
        r = ()
        for v in value:
            if bitNo:
                bitNo = bitNo - 1
            else:
                bitNo = 7
                r = r + (byte, )
                byte = 0
            if v == '0':
                v = 0
            elif v == '1':
                v = 1
            else:
                raise error.PyAsn1Error(
                    'Non-binary OCTET STRING initializer %s' % (v, ))
            byte = byte | (v << bitNo)
        return octets.ints2octs(r + (byte, ))

    def fromHexString(self, value):
        r = p = ()
        for v in value:
            if p:
                r = r + (int(p + v, 16), )
                p = ()
            else:
                p = v
        if p:
            r = r + (int(p + '0', 16), )
        return octets.ints2octs(r)

    def prettyOut(self, value):
        if sys.version_info[0] <= 2:
            numbers = tuple([ord(x) for x in value])
        else:
            numbers = tuple(value)
        if [x for x in numbers if x < 32 or x > 126]:
            return '0x' + ''.join(['%.2x' % x for x in numbers])
        else:
            return str(value)

    def __repr__(self):
        if self._value is base.noValue:
            return self.__class__.__name__ + '()'
        if [x for x in self.asNumbers() if x < 32 or x > 126]:
            return self.__class__.__name__ + '(hexValue=\'' + ''.join(
                ['%.2x' % x for x in self.asNumbers()]) + '\')'
        else:
            return self.__class__.__name__ + '(\'' + self.prettyOut(
                self._value) + '\')'

    if sys.version_info[0] <= 2:

        def __str__(self):
            return str(self._value)

        def __unicode__(self):
            return self._value.decode(self._encoding, 'ignore')

        def asOctets(self):
            return self._value

        def asNumbers(self):
            if self.__intValue is None:
                self.__intValue = tuple([ord(x) for x in self._value])
            return self.__intValue
    else:

        def __str__(self):
            return self._value.decode(self._encoding, 'ignore')

        def __bytes__(self):
            return self._value

        def asOctets(self):
            return self._value

        def asNumbers(self):
            if self.__intValue is None:
                self.__intValue = tuple(self._value)
            return self.__intValue

    # Immutable sequence object protocol

    def __len__(self):
        if self._len is None:
            self._len = len(self._value)
        return self._len

    def __getitem__(self, i):
        if isinstance(i, slice):
            return self.clone(operator.getitem(self._value, i))
        else:
            return self._value[i]

    def __add__(self, value):
        return self.clone(self._value + self.prettyIn(value))

    def __radd__(self, value):
        return self.clone(self.prettyIn(value) + self._value)

    def __mul__(self, value):
        return self.clone(self._value * value)

    def __rmul__(self, value):
        return self * value
Ejemplo n.º 26
0
    namedtype.NamedType('value', char.TeletexString().subtype(
        subtypeSpec=constraint.ValueSizeConstraint(1, ub_domain_defined_attribute_value_length)))
)

id_pkix = _OID(1, 3, 6, 1, 5, 5, 7)

id_qt = _OID(id_pkix, 2)


class PresentationAddress(univ.Sequence):
    pass


PresentationAddress.componentType = namedtype.NamedTypes(
    namedtype.OptionalNamedType('pSelector', univ.OctetString().subtype(
        explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))),
    namedtype.OptionalNamedType('sSelector', univ.OctetString().subtype(
        explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1))),
    namedtype.OptionalNamedType('tSelector', univ.OctetString().subtype(
        explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))),
    namedtype.NamedType('nAddresses', univ.SetOf(componentType=univ.OctetString()).subtype(
        explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3)))
)


class AlgorithmIdentifier(univ.Sequence):
    pass


AlgorithmIdentifier.componentType = namedtype.NamedTypes(
    namedtype.NamedType('algorithm', univ.ObjectIdentifier()),
Ejemplo n.º 27
0
class ObjectIdentifier(base.AbstractSimpleAsn1Item):
    tagSet = baseTagSet = tag.initTagSet(
        tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x06))

    def __add__(self, other):
        return self.clone(self._value + other)

    def __radd__(self, other):
        return self.clone(other + self._value)

    def asTuple(self):
        return self._value

    # Sequence object protocol

    def __len__(self):
        if self._len is None:
            self._len = len(self._value)
        return self._len

    def __getitem__(self, i):
        if isinstance(i, slice):
            return self.clone(operator.getitem(self._value, i))
        else:
            return self._value[i]

    def __str__(self):
        return self.prettyPrint()

    def index(self, suboid):
        return self._value.index(suboid)

    def isPrefixOf(self, value):
        """Returns true if argument OID resides deeper in the OID tree"""
        l = len(self)
        if l <= len(value):
            if self._value[:l] == value[:l]:
                return 1
        return 0

    def prettyIn(self, value):
        """Dotted -> tuple of numerics OID converter"""
        if isinstance(value, tuple):
            pass
        elif isinstance(value, ObjectIdentifier):
            return tuple(value)
        elif isinstance(value, str):
            r = []
            for element in [x for x in value.split('.') if x != '']:
                try:
                    r.append(int(element, 0))
                except ValueError:
                    raise error.PyAsn1Error(
                        'Malformed Object ID %s at %s: %s' %
                        (str(value), self.__class__.__name__,
                         sys.exc_info()[1]))
            value = tuple(r)
        else:
            try:
                value = tuple(value)
            except TypeError:
                raise error.PyAsn1Error(
                    'Malformed Object ID %s at %s: %s' %
                    (str(value), self.__class__.__name__, sys.exc_info()[1]))

        for x in value:
            if not isinstance(x, intTypes) or x < 0:
                raise error.PyAsn1Error('Invalid sub-ID in %s at %s' %
                                        (value, self.__class__.__name__))

        return value

    def prettyOut(self, value):
        return '.'.join([str(x) for x in value])
Ejemplo n.º 28
0
class IpAddress(univ.OctetString):
    tagSet = univ.OctetString.tagSet.tagImplicitly(
        tag.Tag(tag.tagClassApplication, tag.tagFormatSimple, 0x00))
    subtypeSpec = univ.OctetString.subtypeSpec + constraint.ValueSizeConstraint(
        4, 4)
Ejemplo n.º 29
0
class Enumerated(Integer):
    tagSet = baseTagSet = tag.initTagSet(
        tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 0x0A))
Ejemplo n.º 30
0
class RevokedInfo(univ.Sequence):
    componentType = namedtype.NamedTypes(namedtype.NamedType('revocationTime', useful.GeneralizedTime()), namedtype.OptionalNamedType('revocationReason', CRLReason().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))))