def test_construct(self): asn1 = rfc2459.Extension() asn1['extnID'] = rfc2459.univ.ObjectIdentifier('1.2.3.4') asn1['critical'] = False asn1['extnValue'] = "foobar" ext = extension.construct_extension(asn1) self.assertIsInstance(ext, extension.X509Extension)
def test_unknown_extension_str(self): asn1 = rfc2459.Extension() asn1['extnID'] = rfc2459.univ.ObjectIdentifier('1.2.3.4') asn1['critical'] = False asn1['extnValue'] = "foobar" ext = extension.X509Extension(asn1) self.assertEqual("1.2.3.4: <unknown>", str(ext))
def _encode_extension(oid, critical, value): ext = rfc2459.Extension() ext['extnID'] = univ.ObjectIdentifier(oid) ext['critical'] = univ.Boolean(critical) ext['extnValue'] = univ.Any(encoder.encode(univ.OctetString(value))) ext = encoder.encode(ext) return ext
def _build_extension_netscapeURL(strurl): ext = rfc2459.Extension() extoid = utility.OID_ns_netscape_base_url extval = char.IA5String(strurl) encapsulated = univ.OctetString(encoder.encode(extval)) ext.setComponentByName('extnID', extoid) ext.setComponentByName('extnValue', encapsulated) return ext
def addExtension(self, extensionType, extensionValue): if not self.extensions: self.extensions = [] encapsulated = univ.OctetString(encoder.encode(extensionValue)) extension = rfc2459.Extension() extension.setComponentByName('extnID', extensionType) extension.setComponentByName('extnValue', encapsulated) self.extensions.append(extension)
def _build_key_usage(value): ext = rfc2459.Extension() extoid = utility.OID_ku extval = rfc2459.KeyUsage(value) encapsulated = univ.OctetString(encoder.encode(extval)) ext.setComponentByName('extnID', extoid) ext.setComponentByName('extnValue', encapsulated) return ext
def test_critical(self): asn1 = rfc2459.Extension() asn1['extnID'] = rfc2459.univ.ObjectIdentifier('1.2.3.4') asn1['critical'] = False asn1['extnValue'] = "foobar" ext = extension.construct_extension(asn1) self.assertFalse(ext.get_critical()) ext.set_critical(True) self.assertTrue(ext.get_critical())
def _build_extended_key_usage(ekus): ext = rfc2459.Extension() extoid = utility.OID_eku extval = rfc2459.ExtKeyUsageSyntax() for i, eku in enumerate(ekus): extval.setComponentByPosition(i, eku) encapsulated = univ.OctetString(encoder.encode(extval)) ext.setComponentByName('extnID', extoid) ext.setComponentByName('extnValue', encapsulated) return ext
def CreateExtension(oid='1.2.3.4', critical=False): ext = rfc2459.Extension() ext.setComponentByName('extnID', univ.ObjectIdentifier(oid)) ext.setComponentByName('extnValue', 'DEADBEEF') if critical: ext.setComponentByName('critical', univ.Boolean('True')) else: ext.setComponentByName('critical', univ.Boolean('False')) return ext
def __init__(self, ext=None): if ext is None: if self.spec is None: raise errors.X509Error("cannot create generic extension") self._ext = rfc2459.Extension() self._ext['extnID'] = self._oid self._set_value(self._get_default_value()) else: if not isinstance(ext, rfc2459.Extension): raise errors.X509Error("extension has incorrect type") self._ext = ext
def __encode_extension(self, oid, critical, value): # TODO: have another proxy for crypto_x509.Extension which would # provide public_bytes on the top of what python-cryptography has ext = rfc2459.Extension() # TODO: this does not have to be so weird, pyasn1 now has codecs # which are capable of providing python-native types ext['extnID'] = univ.ObjectIdentifier(oid) ext['critical'] = univ.Boolean(critical) ext['extnValue'] = univ.Any(encoder.encode(univ.OctetString(value))) ext = encoder.encode(ext) return ext
def addExtension(self, extensionType, extensionValue, critical): if not self.extensions: self.extensions = [] encapsulated = univ.OctetString(encoder.encode(extensionValue)) extension = rfc2459.Extension() extension.setComponentByName('extnID', extensionType) # critical is either the string '[critical]' or None. # We only care whether or not it is truthy. if critical: extension.setComponentByName('critical', True) extension.setComponentByName('extnValue', encapsulated) self.extensions.append(extension)
def __init__(self, oid, value, critical=False): """Общий класс для всех видов расширений :oid: OID расширения :value: значение в ASN.1 """ self.asn = rfc2459.Extension() self.asn.setComponentByName('extnID', univ.ObjectIdentifier(oid)) self.asn.setComponentByName('critical', univ.Boolean(critical)) self.asn.setComponentByName('extnValue', encoder.encode(univ.OctetString(value)))
def addExtension(self, extensionType, extensionValue, critical): if not self.extensions: self.extensions = [] encapsulated = univ.OctetString(encoder.encode(extensionValue)) extension = rfc2459.Extension() extension['extnID'] = extensionType # critical is either the string '[critical]' or None. # We only care whether or not it is truthy. if critical: extension['critical'] = True extension['extnValue'] = encapsulated self.extensions.append(extension)
def __encode_extension(self, oid, critical, value): # TODO: have another proxy for crypto_x509.Extension which would # provide public_bytes on the top of what python-cryptography has ext = rfc2459.Extension() # TODO: this does not have to be so weird, pyasn1 now has codecs # which are capable of providing python-native types ext['extnID'] = univ.ObjectIdentifier(oid) ext['critical'] = univ.Boolean(critical) if pyasn1.__version__.startswith('0.3'): # pyasn1 <= 0.3.7 needs explicit encoding # see https://pagure.io/freeipa/issue/7685 value = encoder.encode(univ.OctetString(value)) ext['extnValue'] = univ.Any(value) ext = encoder.encode(ext) return ext
def _build_extensionFromAttributeExtension(extension): extoid = extension[0] if len(extension) == 3: critical = extension[1] value = extension[2] extval = value ext = rfc2459.Extension() encapsulated = extval ext.setComponentByName('extnID', extoid) ext.setComponentByName('critical', univ.Boolean(critical)) ext.setComponentByName('extnValue', encapsulated) return ext elif len(extension) == 2: value = extension[1] extval = value ext = rfc2314.Extension() encapsulated = extval ext.setComponentByName('extnID', extoid) ext.setComponentByName('extnValue', encapsulated) return ext else: return None
def CreateExtension(): ext = rfc2459.Extension() ext.setComponentByName('extnID', univ.ObjectIdentifier('1.2.3.4')) ext.setComponentByName('extnValue', 'DEADBEEF') return ext
request = Request() certid = CertID() request['reqCert'] = certid certid['hashAlgorithm'] = rfc2459.AlgorithmIdentifier()\ .setComponentByName('algorithm', rfc2437.id_sha1)\ .setComponentByName('parameters', univ.Any(hexValue='0500')) certid['issuerNameHash'] = univ.OctetString( hexValue='01cb3044531fa8618a68d3c60596ab0555866b09') certid['issuerKeyHash'] = univ.OctetString( hexValue='31c3791bbaf553d717e0897a2d176c0ab32b9d33') certid['serialNumber'] = rfc2459.CertificateSerialNumber(0) req['tbsRequest']['requestList'] = univ.SequenceOf( componentType=Request()).setComponentByPosition(0, request) reqExts = rfc2459.Extensions().subtype( explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2)) reqExt = rfc2459.Extension() reqExt['extnID'] = univ.ObjectIdentifier('1.3.6.1.5.5.7.48.1.2') reqExt['critical'] = univ.Boolean('False') reqExt['extnValue'] = univ.Any( hexValue='04120410236e5193af7958f49edcc756ed6c6dd3') reqExts[0] = reqExt req['tbsRequest']['requestExtensions'] = reqExts print(req.prettyPrint()) print(encoder.encode(req)) else: with open(sys.argv[1], 'rb') as fp: for t in decoder.decode(fp.read(), asn1Spec=OCSPRequest()): if hasattr(t, 'prettyPrint'): print(t.prettyPrint()) else:
def build_payload(): # initializations tbsReq = TBSRequest() certid = CertID() request = Request() requestList = univ.SequenceOf(componentType=Request()) req = OCSPRequest() reqExts = rfc2459.Extensions().subtype( explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2)) reqExt = rfc2459.Extension() signature = Signature() certs = univ.SequenceOf(componentType=rfc2459.Certificate()).subtype( explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0) ) cert = rfc2459.Certificate() name = rfc2459.GeneralName() # assignments certid['hashAlgorithm'] = rfc2459.AlgorithmIdentifier()\ .setComponentByName('algorithm', ALGORITHM)\ .setComponentByName('parameters', univ.Any(hexValue=ALGO_PARAMS_HEX)) certid['issuerNameHash'] = univ.OctetString(hexValue=ISSUER_NAME_HASH) certid['issuerKeyHash'] = univ.OctetString(hexValue=ISSUER_KEY_HASH) certid['serialNumber'] = rfc2459.CertificateSerialNumber(SERIAL_NUMBER) request['reqCert'] = certid # optional field #request['singleRequestExtension'] = reqExt reqExt['extnID'] = univ.ObjectIdentifier('1.3.6.1.5.5.7.48.1.2') reqExt['critical'] = univ.Boolean('False') reqExt['extnValue'] = univ.Any(hexValue='04120410236e5193af7958f49edcc756ed6c6dd3') reqExts[0] = reqExt requestList[0] = request # optional # TODO: fill name? #tbsReq['requestorName'] = name tbsReq['requestList'] = requestList # optional tbsReq['requestExtensions'] = reqExts tbsReq['version'] = Version(0).subtype( explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)) # optional # TODO fill cert? signature['signatureAlgorithm'] = rfc2459.AlgorithmIdentifier()\ .setComponentByName('algorithm', rfc2437.sha1WithRSAEncryption) signature['signature'] = univ.BitString("'010101010101'B") certs[0] = cert signature['certs'] = certs req['tbsRequest'] = tbsReq # optional signature #req['optionalSignature'] = signature return req
def encode(cls, pki_key: object, **kwargs): # Algorithm ID alg_oid = cls.ALG_OID if type( cls.ALG_OID) is str else cls.ALG_OID(pki_key) alg_id = rfc2459.AlgorithmIdentifier() alg_id['algorithm'] = ObjectIdentifier(alg_oid) if cls.PARAM_ENCODER: alg_id['parameters'] = Any( encoder.encode(cls.PARAM_ENCODER.encode(pki_key))) # Serial number serial_num = rfc2459.CertificateSerialNumber( kwargs.get('serial_number') or 0) # Validity (time valid) not_before = kwargs.get('not_before') or datetime.now() not_after = kwargs.get('not_after') or not_before.replace( year=not_before.year + 1) validity = rfc2459.Validity() validity['notBefore'] = rfc2459.Time() validity['notBefore']['utcTime'] = UTCTime.fromDateTime(not_before) validity['notAfter'] = rfc2459.Time() validity['notAfter']['utcTime'] = UTCTime.fromDateTime(not_after) # Public key serialization pub_info = rfc2459.SubjectPublicKeyInfo() pub_info['algorithm'] = alg_id pub_info['subjectPublicKey'] = cls.PUB_KEY_ENCODER.encode(pki_key) # Issuer RDN issuer = rfc2459.Name() issuer.setComponentByPosition( 0, parse_rdn(kwargs.get('issuer') or 'CN=ca')) # Subject RDN subject = rfc2459.Name() subject.setComponentByPosition( 0, parse_rdn(kwargs.get('subject') or 'CN=ca')) # Signature algorithm signing_key = kwargs.get('signing_key') or pki_key if not (kwargs.get('signing_alg') or hasattr(signing_key, "X509_SIGNING_DEFAULT")): raise ValueError( "'signing_alg' not specified and 'signing_key' has no default algorithm" ) signing_alg = (kwargs.get('signing_alg') or signing_key.X509_SIGNING_DEFAULT).value signature_alg = rfc2459.AlgorithmIdentifier() signature_alg['algorithm'] = SIGNING_ALG_OIDS[signing_alg.name] if cls.PARAM_ENCODER: signature_alg['parameters'] = Any( encoder.encode(cls.PARAM_ENCODER.encode(pki_key))) # Extensions extensions = rfc2459.Extensions().subtype( explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3)) if kwargs.get('ca') and kwargs.get('ca') == True: # SKI pkey_bytes = Bytes(int(pub_info['subjectPublicKey'])) ski_ext = rfc2459.Extension() ski_ext['extnID'] = ObjectIdentifier([2, 5, 29, 14]) ski_ext['extnValue'] = OctetString( encoder.encode( rfc2459.SubjectKeyIdentifier(SHA1().hash(pkey_bytes)))) # CA basic constraint ca_value = rfc2459.BasicConstraints() ca_value.setComponentByName('cA', True) ca_ext = rfc2459.Extension() ca_ext.setComponentByName('extnID', '2.5.29.19') ca_ext.setComponentByName('critical', True) ca_ext.setComponentByName('extnValue', OctetString(encoder.encode(ca_value))) extensions.setComponentByPosition(0, ski_ext) extensions.setComponentByPosition(1, ca_ext) # Put together the TBSCert tbs_cert = rfc2459.TBSCertificate() tbs_cert['version'] = 2 tbs_cert['serialNumber'] = serial_num tbs_cert['signature'] = signature_alg tbs_cert['issuer'] = issuer tbs_cert['validity'] = validity tbs_cert['subject'] = subject tbs_cert['subjectPublicKeyInfo'] = pub_info tbs_cert['issuerUniqueID'] = kwargs.get('issuer_unique_id') or 10 tbs_cert['subjectUniqueID'] = kwargs.get('subject_unique_id') or 11 if len(extensions): tbs_cert['extensions'] = extensions # Inject or compute the TBSCert signature if kwargs.get('signature_value') is not None: sig_value = Bytes.wrap(kwargs.get('signature_value')).int() else: encoded_tbs = encoder.encode(tbs_cert, asn1Spec=rfc2459.TBSCertificate()) sig_value = signing_alg.sign(signing_key, encoded_tbs) # Build the Cert object cert = rfc2459.Certificate() cert['tbsCertificate'] = tbs_cert cert['signatureAlgorithm'] = signature_alg cert['signatureValue'] = sig_value encoded = encoder.encode(cert, asn1Spec=rfc2459.Certificate()) return X509Certificate.transport_encode(encoded, **kwargs)
def to_asn1(self): extension = rfc2459.Extension() extension["extnID"] = self.oid.to_asn1() extension["critical"] = self.critical extension["extnValue"] = self.data return extension