Beispiel #1
0
 def buildAuthenticatedAttributes(self, value, implicitTag=None):
     """Utility function to build a pyasn1 AuthenticatedAttributes
     object. Useful because when building a SignerInfo, the
     authenticatedAttributes needs to be tagged implicitly, but when
     signing an AuthenticatedAttributes, it needs the explicit SET
     tag."""
     if implicitTag:
         authenticatedAttributes = rfc2315.Attributes().subtype(
             implicitTag=implicitTag)
     else:
         authenticatedAttributes = rfc2315.Attributes()
     contentTypeAttribute = rfc2315.Attribute()
     # PKCS#9 contentType
     contentTypeAttribute['type'] = univ.ObjectIdentifier(
         '1.2.840.113549.1.9.3')
     contentTypeAttribute['values'] = univ.SetOf(rfc2459.AttributeValue())
     # PKCS#7 data
     contentTypeAttribute['values'][0] = univ.ObjectIdentifier(
         '1.2.840.113549.1.7.1')
     authenticatedAttributes[0] = contentTypeAttribute
     hashAttribute = rfc2315.Attribute()
     # PKCS#9 messageDigest
     hashAttribute['type'] = univ.ObjectIdentifier('1.2.840.113549.1.9.4')
     hashAttribute['values'] = univ.SetOf(rfc2459.AttributeValue())
     hashAttribute['values'][0] = univ.OctetString(hexValue=value)
     authenticatedAttributes[1] = hashAttribute
     return authenticatedAttributes
class EnvelopedData(univ.Sequence):
    componentType = namedtype.NamedTypes(
        NamedType('CMSVersion', univ.Integer()),
        namedtype.OptionalNamedType('originatorInfo', _c(0, OriginatorInfo())),
        NamedType('recipientInfos',
                  univ.SetOf(componentType=rfc2315.RecipientInfo())),
        NamedType('encryptedContentInfo', EncryptedContentInfo()),
        namedtype.OptionalNamedType(
            'unprotectedAttrs', _c(1, univ.SetOf(componentType=Attribute()))))
class SignedData(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('version', CMSVersion()),
        namedtype.NamedType('digestAlgorithms',
                            univ.SetOf(componentType=AlgorithmIdentifier())),
        # DigestAlgorithmIdentifier
        namedtype.NamedType('encapContentInfo',
                            signedAuthPack()),  # EncapsulatedContentInfo
        _sequence_optional_component('certificates', 0,
                                     univ.Any()),  # CertificateSet NEED CHANGE
        _sequence_optional_component(
            'crls ', 1, univ.Integer()),  # RevocationInfoChoices NEED CHANGE
        namedtype.NamedType('signerInfos',
                            univ.SetOf(componentType=SignerInfo()))  #
    )
Beispiel #4
0
class TRSEntry(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('uuid', ldap.LDAPString()),
        namedtype.NamedType('dn', ldap.LDAPDN()),
        namedtype.NamedType('entry', univ.SetOf(componentType=TRSAttribute())))

    def prettyPrint(self, scope=0):
        scope = scope + 1
        r = self.__class__.__name__ + ':\n'
        scopestr = ' ' * scope
        r = r + '%sdn: %s\n%suuid: %s\n' % (scopestr, self._componentValues[1],
                                            scopestr, self._componentValues[0])
        for ii in range(0, len(self._componentValues[2])):
            trsattr = self._componentValues[2][ii]
            name = trsattr[0]
            vals = trsattr[1]
            for jj in range(0, len(vals)):
                val = vals[jj][0]
                r = r + '%s%s: %s\n' % (scopestr, name, val)
                if len(vals[jj][1]):
                    r = r + '\n%sextra-%s: %s' % (scopestr, name,
                                                  str(vals[jj][1]))
        return r

    def check(self):
        for ii in range(0, len(self._componentValues[2])):
            trsattr = self._componentValues[2][ii]
            vals = trsattr[1]
            for jj in range(0, len(vals)):
                # want to know if the extra field ever has any data in it
                assert (len(vals[jj][1]) == 0)
Beispiel #5
0
class PresentationAddress(univ.Sequence):
    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.OptionalNamedType('nAddresses', univ.SetOf(componentType=univ.OctetString()).subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3), subtypeSpec=constraint.ValueSizeConstraint(1, MAX))),
    )
Beispiel #6
0
class Attribute(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('type', AttributeType()),
        namedtype.NamedType('values',
                            univ.SetOf(componentType=AttributeValue()),
                            openType=opentype.OpenType(
                                'type', certificateAttributesMap)))
Beispiel #7
0
def _build_extension_request(extensions):
    SUPPORTED_EXTENSIONS = {
        'subjectAlternativeName':
        (rfc2314.id_ce_subjectAltName, _build_subject_alt_name),
        'x509basicConstraints':
        (rfc2314.id_ce_basicConstraints, _build_basic_constraints),
        'x509v3KeyUsage': (rfc2314.id_ce_keyUsage, _build_key_usage),
        'x509v3ExtendedKeyUsage':
        (rfc2314.id_ce_extKeyUsage, _build_extended_key_usage),
    }

    count = 0
    exts = rfc2314.Extensions()
    for key, critical, value in extensions:
        if key in SUPPORTED_EXTENSIONS:
            extoid, builder = SUPPORTED_EXTENSIONS[key]
            extval = builder(value)
            ext = rfc2314.Extension()
            encapsulated = univ.OctetString(encoder.encode(extval))
            ext.setComponentByName('extnID', extoid)
            ext.setComponentByName('critical', univ.Boolean(critical))
            ext.setComponentByName('extnValue', encapsulated)

            exts.setComponentByPosition(count, ext)
            count += 1
    if count > 0:
        retval = univ.SetOf(componentType=rfc2314.AttributeTypeAndValue())
        retval.setComponentByPosition(0, exts)
    return retval
class IssuerAndSerialNumber1(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType(
            'issuer',
            univ.SequenceOf(componentType=univ.SetOf(
                componentType=AttributeTypeAndValue()))),
        namedtype.NamedType('serialNumber', univ.Integer()))
Beispiel #9
0
class AttributeList(univ.SequenceOf):
    componentType = univ.Sequence(
        componentType=namedtype.NamedTypes(
           namedtype.NamedType('type', AttributeDescription()),
           namedtype.NamedType('vals', univ.SetOf(componentType=AttributeValue()))
        )
    )
Beispiel #10
0
class Attribute(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('type', AttributeDescription()),
        namedtype.NamedType(
            'vals',
            univ.SetOf(componentType=AttributeValue()).subtype(
                subtypeSpec=constraint.ValueSizeConstraint(1, maxInt))))
Beispiel #11
0
class Clearance(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('policyId',
            univ.ObjectIdentifier()),
        namedtype.DefaultedNamedType('classList',
            ClassList().subtype(value='unclassified')),
        namedtype.OptionalNamedType('securityCategories',
            univ.SetOf(componentType=SecurityCategory()))
    )
 def setUp(self):
     openType = opentype.OpenType('id', {
         1: univ.Integer(),
         2: univ.OctetString()
     })
     self.s = univ.Sequence(componentType=namedtype.NamedTypes(
         namedtype.NamedType('id', univ.Integer()),
         namedtype.NamedType('blob',
                             univ.SetOf(componentType=univ.Any()),
                             openType=openType)))
Beispiel #13
0
class TRSEntryReq(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('unknownInt0', TRSEnum()),
        namedtype.NamedType('trsentryset',
                            univ.SetOf(componentType=TRSEntrySeq())))

    def check(self):
        assert (self.getComponentByName('unknownInt0')._value == 0)
        assert (len(self[1]) == 1)
        self[1][0].check()
Beispiel #14
0
class Filter(univ.Choice):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType(
            'and',
            univ.SetOf(componentType=Filter2()).subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 0))),
        namedtype.NamedType(
            'or',
            univ.SetOf(componentType=Filter2()).subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 1))),
        namedtype.NamedType(
            'not',
            Filter2().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 2))),
        namedtype.NamedType(
            'equalityMatch',
            AttributeValueAssertion().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 3))),
        namedtype.NamedType(
            'substrings',
            SubstringFilter().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 4))),
        namedtype.NamedType(
            'greaterOrEqual',
            AttributeValueAssertion().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 5))),
        namedtype.NamedType(
            'lessOrEqual',
            AttributeValueAssertion().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 6))),
        namedtype.NamedType(
            'present',
            AttributeDescription().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 7))),
        namedtype.NamedType(
            'approxMatch',
            AttributeValueAssertion().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 8))),
        namedtype.NamedType(
            'extensibleMatch',
            MatchingRuleAssertion().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 9))))
Beispiel #15
0
class DistributionPointName(univ.Choice):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType(
            'fullName',
            GeneralNames().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 0))),
        namedtype.NamedType(
            'nameRelativeToCRLIssuer',
            univ.SetOf().subtype(implicitTag=tag.Tag(tag.tagClassContext,
                                                     tag.tagFormatSimple, 1))),
    )
 def setUp(self):
     openType = opentype.OpenType('id', {
         1: univ.Integer(),
         2: univ.OctetString()
     })
     self.s = univ.Sequence(componentType=namedtype.NamedTypes(
         namedtype.NamedType('id', univ.Integer()),
         namedtype.NamedType('blob',
                             univ.SetOf(componentType=univ.Any().subtype(
                                 explicitTag=tag.Tag(
                                     tag.tagClassContext,
                                     tag.tagFormatSimple, 3))),
                             openType=openType)))
Beispiel #17
0
class Clearance_rfc3281(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('policyId',
            univ.ObjectIdentifier().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 0))),
        namedtype.DefaultedNamedType('classList',
            ClassList().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 1)).subtype(
                    value='unclassified')),
        namedtype.OptionalNamedType('securityCategories',
            univ.SetOf(componentType=SecurityCategory()).subtype(
                implicitTag=tag.Tag(
                    tag.tagClassContext, tag.tagFormatSimple, 2)))
    )
Beispiel #18
0
def generateMetaDataAsn(remoteComputer, issuer):
    data = MetaData()
    a = univ.SequenceOf(univ.SetOf(CertIssuer()))
    a[0][0]['1'] = '2.5.4.3'
    a[0][0]['Info'] = issuer.encode("utf-16-be")
    data['1'][0]['certIssuer'] = encode(a)
    data['Info']['pku2u'] = "WELLKNOWN:PKU2U"
    data['Info']['clientInfo']['clientType'] = -128
    data['Info']['clientInfo']['clientName'][0] = remoteComputer

    data1 = CertInfos()
    data1['certInfos']['certInfo'] = encode(a)

    return encode(data).encode('hex')
Beispiel #19
0
def check_signature(tsa_cert: str, signature, data, hash_str):
    # TODO invoke different hash function based on hash_str
    try:
        data_ = encoder.encode(data, asn1Spec=univ.SetOf())  # encode with asn1Spec univ.SetOf()
        with open(tsa_cert, 'r') as pem_file:
            cert_pem = pem.readPemFromFile(pem_file)
        pub_key = RSA.import_key(cert_pem)
        hash_obj = SHA1.new()
        hash_obj.update(data_)
        crypto_signature.new(pub_key).verify(hash_obj, signature.asOctets())
    except Exception as e:
        logging.error('Check signature: Failure', exc_info=True)
        raise e
    logging.info('Check signature: Success')
    return True
class SignerInfo(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('version', CMSVersion()),
        namedtype.NamedType('sid', SignerIdentifier()),
        namedtype.NamedType('digestAlgorithm', AlgorithmIdentifier()),
        # DigestAlgorithmIdentifier
        _sequence_optional_component('signedAttrs', 0, univ.Any()),
        # SignedAttributes @ shouldnt be set, but set in documentation
        namedtype.NamedType(
            'signatureAlgorithm',
            AlgorithmIdentifier()),  # SignatureAlgorithmIdentifier
        namedtype.NamedType('signature', SignatureValue()),
        _sequence_optional_component(
            'unsignedAttrs', 1,
            univ.SetOf(componentType=Attribute()))  # UnsignedAttributes
    )
Beispiel #21
0
def calc_signerinfo_digest(signer_info, digest_algo):
    """Calcuate the digest of authenticatedAttributes.

    Args:
        signer_info (SignerInfo object): object with authenticatedAttributes
                                         over which we will calculate the digest.
        digest_algo (str): digest algorithm to use. e.g. 'sha256'

    Returns:
        digest as a byte string

    """
    auth_attrs = univ.SetOf(componentType=Attribute())
    for i, v in enumerate(signer_info["authenticatedAttributes"]):
        auth_attrs[i] = v
    auth_attrs_encoded = der_encode(auth_attrs)

    return hashlib.new(digest_algo, auth_attrs_encoded).digest()
Beispiel #22
0
 def setUp(self):
     self.s1 = univ.SetOf(componentType=univ.OctetString(''))
Beispiel #23
0
                idx = idx - 1
                compSubs.append(
                    encodeFun(client[idx], defMode, maxChunkSize)
                    )
            compSubs.sort()  # perhaps padding's not needed
            substrate = null
            for compSub in compSubs:
                substrate += compSub
        return substrate, 1

tagMap = encoder.tagMap.copy()
tagMap.update({
    univ.Boolean.tagSet: BooleanEncoder(),
    univ.BitString.tagSet: BitStringEncoder(),
    univ.OctetString.tagSet: OctetStringEncoder(),
    univ.SetOf().tagSet: SetOfEncoder()  # conflcts with Set
    })

typeMap = encoder.typeMap.copy()
typeMap.update({
    univ.Set.typeId: SetOfEncoder(),
    univ.SetOf.typeId: SetOfEncoder()
    })

class Encoder(encoder.Encoder):
    def __call__(self, client, defMode=0, maxChunkSize=0):
        return encoder.Encoder.__call__(self, client, defMode, maxChunkSize)

encode = Encoder(tagMap, typeMap)

# EncoderFactory queries class instance and builds a map of tags -> encoders
Beispiel #24
0
 def setUp(self):
     BaseTestCase.setUp(self)
     self.s = univ.SetOf(componentType=univ.OctetString())
Beispiel #25
0
 def testDefMode4(self):
     s = univ.SetOf()
     s.append(univ.OctetString('a'))
     s.append(univ.OctetString('b'))
     assert encoder.encode(s) == ints2octs(
         (49, 128, 4, 1, 97, 4, 1, 98, 0, 0))
Beispiel #26
0
 def testEmpty(self):
     s = univ.SetOf()
     assert encoder.encode(s) == ints2octs((49, 128, 0, 0))
Beispiel #27
0
        subtypeSpec=constraint.ValueSizeConstraint(0, ub_domain_name_length)))
)


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 ExtendedNetworkAddress(univ.Choice):
    pass


ExtendedNetworkAddress.componentType = namedtype.NamedTypes(
    namedtype.NamedType(
        'e163-4-address', univ.Sequence(
            componentType=namedtype.NamedTypes(
                namedtype.NamedType('number', char.NumericString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, ub_e163_4_number_length)).subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))),
                namedtype.OptionalNamedType('sub-address', char.NumericString().subtype(subtypeSpec=constraint.ValueSizeConstraint(1, ub_e163_4_sub_address_length)).subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1)))
            )
        )
Beispiel #28
0
    pass


Clearance.componentType = namedtype.NamedTypes(
    namedtype.NamedType(
        'policyId',
        univ.ObjectIdentifier().subtype(
            implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))),
    namedtype.DefaultedNamedType(
        'classList',
        ClassList().subtype(implicitTag=tag.Tag(
            tag.tagClassContext, tag.tagFormatSimple, 1)).subtype(
                value="unclassified")),
    namedtype.OptionalNamedType(
        'securityCategories',
        univ.SetOf(componentType=SecurityCategory()).subtype(
            implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2))))


class AttCertVersion(univ.Integer):
    pass


AttCertVersion.namedValues = namedval.NamedValues(('v2', 1))

id_aca = _buildOid(rfc3280.id_pkix, 10)

id_at_clearance = _buildOid(2, 5, 1, 5, 55)


class AttrSpec(univ.SequenceOf):
    pass
Beispiel #29
0
    return univ.ObjectIdentifier(output)


class AttributeValue(univ.Any):
    pass


class Attribute(univ.Sequence):
    pass


Attribute.componentType = namedtype.NamedTypes(
    namedtype.NamedType('attrType', univ.ObjectIdentifier()),
    namedtype.NamedType('attrValues',
                        univ.SetOf(componentType=AttributeValue())))


class SignedAttributes(univ.SetOf):
    pass


SignedAttributes.componentType = Attribute()
SignedAttributes.subtypeSpec = constraint.ValueSizeConstraint(1, MAX)


class OtherRevocationInfoFormat(univ.Sequence):
    pass


OtherRevocationInfoFormat.componentType = namedtype.NamedTypes(
Beispiel #30
0
    namedtype.NamedType(
        '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()),
    namedtype.NamedType('certificationRequest', CertificationRequest()))


class TaggedRequest(univ.Choice):