def encode(ecdsa_key: object, **kwargs): alg_id = SequenceOf() alg_id.setComponentByPosition( 0, ObjectIdentifier([1, 2, 840, 10045, 2, 1])) alg_id.setComponentByPosition( 1, ObjectIdentifier( ber_decoder.decode(b'\x06' + bytes([len(ecdsa_key.G.curve.oid)]) + ecdsa_key.G.curve.oid)[0].asTuple())) zero_fill = math.ceil(ecdsa_key.G.curve.q.bit_length() / 8) params_seq = Sequence() params_seq.setComponentByPosition(0, Integer(1)) params_seq.setComponentByPosition( 1, OctetString(Bytes(ecdsa_key.d).zfill(zero_fill))) params_seq.setComponentByPosition( 2, PublicPoint(ecdsa_key.format_public_point())) param_oct = OctetString(encoder.encode(params_seq)) top_seq = Sequence() top_seq.setComponentByPosition(0, Integer(0)) top_seq.setComponentByPosition(1, alg_id) top_seq.setComponentByPosition(2, param_oct) encoded = encoder.encode(top_seq) encoded = PKCS8ECDSAPrivateKey.transport_encode(encoded, **kwargs) return encoded
class MechTypes(object): # Currently only NTLMSSP is supported, with the aim to support Kerberos MS_KRB5 = ObjectIdentifier('1.2.840.48018.1.2.2') KRB5 = ObjectIdentifier('1.2.840.113554.1.2.2') KRB5_U2U = ObjectIdentifier('1.2.840.113554.1.2.2.3') NEGOEX = ObjectIdentifier('1.3.6.1.4.1.311.2.2.30') NTLMSSP = ObjectIdentifier('1.3.6.1.4.1.311.2.2.10')
def pkcs7_sign_msg(self, msg): '''WIP: PKCS#7 sign with certificate ''' signed = self.sign(msg) owner_cert_pub = self.pub_cert # signedData (PKCS #7) oi_pkcs7_signed = ObjectIdentifier((1, 2, 840, 113549, 1, 7, 2)) oi_pkcs7_data = ObjectIdentifier((1, 2, 840, 113549, 1, 7, 1)) oi_sha256 = ObjectIdentifier((2, 16, 840, 1, 101, 3, 4, 2, 1)) oi_pkcs7_rsa_enc = ObjectIdentifier((1, 2, 840, 113549, 1, 1, 1)) der = Sequence().setComponentByPosition(0, oi_pkcs7_signed) data = Sequence() data = data.setComponentByPosition(0, Integer(1)) data = data.setComponentByPosition(1, Set().setComponentByPosition(0, Sequence().setComponentByPosition(0, oi_sha256).setComponentByPosition(1, Null('')))) data = data.setComponentByPosition(2, Sequence().setComponentByPosition(0, oi_pkcs7_data).setComponentByPosition(1, Sequence().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)).setComponentByPosition(0, OctetString(hexValue=msg.encode('hex'))))) data = data.setComponentByPosition(3, Sequence().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)).setComponentByPosition(0, owner_cert_pub)) data4001 = Sequence().setComponentByPosition(0, owner_cert_pub[0][3]) data4001 = data4001.setComponentByPosition(1, owner_cert_pub[0][1]) data4002 = Sequence().setComponentByPosition(0, oi_sha256).setComponentByPosition(1, Null('')) data4003 = Sequence().setComponentByPosition(0, oi_pkcs7_rsa_enc).setComponentByPosition(1, Null('')) data4004 = OctetString(hexValue=signed.encode('hex')) data = data.setComponentByPosition(4, Set().setComponentByPosition(0, Sequence().setComponentByPosition(0, Integer(1)).setComponentByPosition(1, data4001).setComponentByPosition(2, data4002).setComponentByPosition(3, data4003).setComponentByPosition(4, data4004))) der = der.setComponentByPosition(1, Sequence().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)).setComponentByPosition(0, data)) return der_encoder.encode(der)
def _decode_authencrypt(self, buff): _, remains = der_decode(buff, ObjectIdentifier()) mac_oid, remains = der_decode(remains, ObjectIdentifier()) encryption_oid, remains = der_decode(remains, ObjectIdentifier()) if self.DEBUG: sys.stderr.write( "Decoded Algorithm OIDS\n Encryption Algorithm OID: {0}\n MAC Algorithm OID: {1}\n" .format(encryption_oid, mac_oid)) return encryption_oid, mac_oid, remains
def walk_iter(self, oid, convert=None): '''Performs a SNMP walk with the given OID and returns a tuple with oid and value. This function will not return values from other SNMP trees than requested. Args: oid (ObjectIdentifier): the OID of the subtree to walk over Keyword Args: convert (function): used to convert the returned value ''' if not isinstance(oid, ObjectIdentifier): oid = ObjectIdentifier(oid) for var in self.walk(oid): oid_ret, val = var[0] oid_tup = tuple(oid_ret) # check if we are in the same subtree as # requested or stop iteration if len(oid_tup) >= len(oid) and not oid_tup[:len(oid)] == oid: return if convert is not None: yield oid_ret, convert(val) else: yield oid_ret, val
def declared_hostinfo(monkeypatch, request): data = [[ ObjectName('.1.3.6.1.2.1.1.2.0'), ObjectIdentifier(request.param['sysobjectid']) ], [ ObjectName('.1.3.6.1.2.1.1.1.0'), OctetString(request.param['description']) ]] get_oids = request.param.get('get_oids') if get_oids: for entry in get_oids: data.append([ ObjectName(get_oids[entry]['oid']), OctetString(get_oids[entry]['value']) ]) if 'walk_oids' in request.param.keys(): get_next_return = [] for extra_oid in request.param['walk_oids']: get_next_return.append([ ObjectName('.' + request.param['walk_oids'][extra_oid]['oid']), OctetString(request.param['walk_oids'][extra_oid]['value']) ]) walk_data = [get_next_return] else: walk_data = None return GetCmd(monkeypatch, return_value=data, walk_data=walk_data, params=request.param)
def scts_from_cert(cert_der): '''Return list of SCTs of the SCTList SAN extension of the certificate. Args: cert_der(bytes): DER encoded ASN.1 Certificate Return: [<ctutlz.rfc6962.SignedCertificateTimestamp>, ...] ''' cert, _ = der_decoder( cert_der, asn1Spec=pyasn1_modules.rfc5280.Certificate()) sctlist_oid = ObjectIdentifier(value='1.3.6.1.4.1.11129.2.4.2') exts = [] if 'extensions' in cert['tbsCertificate'].keys(): exts = [extension for extension in cert['tbsCertificate']['extensions'] if extension['extnID'] == sctlist_oid] if len(exts) != 0: extension_sctlist = exts[0] os_inner_der = extension_sctlist['extnValue'] # type: OctetString() os_inner, _ = der_decoder(os_inner_der, OctetString()) sctlist_hex = os_inner.prettyPrint().split('0x')[-1] sctlist_der = binascii.unhexlify(sctlist_hex) sctlist = SignedCertificateTimestampList(sctlist_der) return [SignedCertificateTimestamp(entry.sct_der) for entry in sctlist.sct_list] return []
def is_ev_cert(ee_cert): '''Return True if ee_cert is an extended validation certificate, else False. Args: ee_cert (EndEntityCert) ''' oids = [] oid_certificate_policies = ObjectIdentifier('2.5.29.32') all_extensions = ee_cert.tbscert.pyasn1['extensions'] if all_extensions is not None: policy_extensions = [ ext for ext in all_extensions if ext['extnID'] == oid_certificate_policies ] if len(policy_extensions) > 0: policy_extension = policy_extensions[0] sequence_der = policy_extension['extnValue'] # type: Sequence() try: sequence, _ = der_decoder(sequence_der, Sequence()) except pyasn1.error.PyAsn1Error: sequence = [] # invalid encoded certificate policy extension for idx in range(len(sequence)): inner_sequence = sequence.getComponentByPosition(idx) oid = inner_sequence.getComponentByPosition(0) oids.append(str(oid)) intersection = list(set(oids) & set(EV_OIDs)) return intersection != []
class InitialContextToken(Sequence): """ [RFC-2743] 3.1. Mechanism-Independent Token Format This section specifies a mechanism-independent level of encapsulating representation for the initial token of a GSS-API context establishment sequence. InitialContextToken ::= [APPLICATION 0] IMPLICIT SEQUENCE { thisMech MechType, innerContextToken NegotiateToken } """ componentType = NamedTypes( NamedType( 'thisMech', ObjectIdentifier() ), NamedType( 'innerContextToken', NegotiateToken() ) ) tagSet = TagSet( Sequence.tagSet, Tag(tagClassApplication, tagFormatConstructed, 0), )
def test_parse_initial_context_token(self): data = b"\x60\x76\x06\x06\x2b\x06\x01\x05" \ b"\x05\x02\xa0\x6c\x30\x6a\xa0\x3c" \ b"\x30\x3a\x06\x0a\x2b\x06\x01\x04" \ b"\x01\x82\x37\x02\x02\x1e\x06\x09" \ b"\x2a\x86\x48\x82\xf7\x12\x01\x02" \ b"\x02\x06\x09\x2a\x86\x48\x86\xf7" \ b"\x12\x01\x02\x02\x06\x0a\x2a\x86" \ b"\x48\x86\xf7\x12\x01\x02\x02\x03" \ b"\x06\x0a\x2b\x06\x01\x04\x01\x82" \ b"\x37\x02\x02\x0a\xa3\x2a\x30\x28" \ b"\xa0\x26\x1b\x24\x6e\x6f\x74\x5f" \ b"\x64\x65\x66\x69\x6e\x65\x64\x5f" \ b"\x69\x6e\x5f\x52\x46\x43\x34\x31" \ b"\x37\x38\x40\x70\x6c\x65\x61\x73" \ b"\x65\x5f\x69\x67\x6e\x6f\x72\x65" actual, rdata = decode(data, asn1Spec=InitialContextToken()) assert rdata == b"" assert actual['thisMech'] == ObjectIdentifier('1.3.6.1.5.5.2') assert isinstance(actual['innerContextToken'], NegotiateToken) actual_token = actual['innerContextToken']['negTokenInit'] assert actual_token['mechTypes'] == [ MechTypes.NEGOEX, MechTypes.MS_KRB5, MechTypes.KRB5, MechTypes.KRB5_U2U, MechTypes.NTLMSSP ] assert actual_token['negHints']['hintName'] == \ "not_defined_in_RFC4178@please_ignore"
def pkcs7_enveloped_msg(self, msg, data, iv="0123456789012345"): """WIP: PKCS#7 envelop msg, data with cert""" oi_pkcs7_rsa_enc = ObjectIdentifier((1, 2, 840, 113549, 1, 1, 1)) oi_pkcs7_data = ObjectIdentifier((1, 2, 840, 113549, 1, 7, 1)) oi_seed_cbc = ObjectIdentifier(id_seed_cbc) der = Sequence().setComponentByPosition( 0, ObjectIdentifier(id_pkcs7_enveloped_data)) data_set = Sequence().setComponentByPosition(0, Integer(0)) data_set = data_set.setComponentByPosition( 1, Sequence().setComponentByPosition( 0, self.pub_cert[0][3]).setComponentByPosition( 1, self.pub_cert[0][1])) data_set = data_set.setComponentByPosition( 2, Sequence().setComponentByPosition( 0, oi_pkcs7_rsa_enc).setComponentByPosition(1, Null(''))) data_set = data_set.setComponentByPosition( 3, OctetString(hexValue=msg.encode('hex'))) data_seq = Sequence().setComponentByPosition(0, oi_pkcs7_data) data_seq = data_seq.setComponentByPosition( 1, Sequence().setComponentByPosition( 0, oi_seed_cbc).setComponentByPosition( 1, OctetString(hexValue=iv.encode('hex')))) data_seq = data_seq.setComponentByPosition( 2, OctetString( hexValue=data.encode('hex')).subtype(implicitTag=tag.Tag( tag.tagClassContext, tag.tagFormatSimple, 0))) data = Sequence().setComponentByPosition(0, Integer(0)) data = data.setComponentByPosition( 1, Set().setComponentByPosition(0, data_set)) data = data.setComponentByPosition(2, data_seq) der = der.setComponentByPosition( 1, Sequence().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)).setComponentByPosition(0, data)) return der_encoder.encode(der)
def tbscert_without_ct_extensions(tbscert): '''Return pyasn1_modules.rfc5280.TBSCertificate instance `cert_pyasn1` without sctlist extension (OID 1.3.6.1.4.1.11129.2.4.3) and poison extension (OID 1.3.6.1.4.1.11129.2.4.2), if any. ''' sctlist_oid = ObjectIdentifier(value='1.3.6.1.4.1.11129.2.4.2') poison_oid = ObjectIdentifier(value='1.3.6.1.4.1.11129.2.4.3') ct_oids = [sctlist_oid, poison_oid] extensions = tbscert['extensions'] without_ct_extensions = extensions.subtype() for extension in extensions: if extension['extnID'] not in ct_oids: without_ct_extensions.append(extension) copy = copy_pyasn1_instance(tbscert) copy['extensions'] = without_ct_extensions return copy
class OtherName(Sequence): # pylint: disable=C0111,R0903 componentType = NamedTypes( NamedType('type-id', ObjectIdentifier()), NamedType( 'value', Any().subtype(explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))))
def test_1_pyasn1(self): """ Test the used methods of pyasn1. """ from pyasn1.type.univ import ObjectIdentifier from pyasn1.codec.der import encoder, decoder oid = encoder.encode(ObjectIdentifier(krb5_mech)) mech, __ = decoder.decode(oid) self.assertEquals(krb5_mech, mech.__str__())
class AlgorithmIdentifier(Sequence): """ AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY DEFINED BY algorithm OPTIONAL } """ componentType = NamedTypes( NamedType('algorithm', ObjectIdentifier()), NamedType('parameters', Any()), )
def parse_ec_params(items, curve_idx, pub_point_idx): from samson.public_key.ecdsa import ECDSA curve_oid = items[curve_idx].asTuple() oid_bytes = ber_encoder.encode(ObjectIdentifier(curve_oid))[2:] curve = WS_OID_LOOKUP[oid_bytes] x_y_bytes = Bytes(int(items[pub_point_idx])) x, y = ECDSA.decode_point(x_y_bytes) return x, y, curve
def encode(eddsa_key: object, **kwargs): alg_id = SequenceOf() alg_id.setComponentByPosition(0, ObjectIdentifier(eddsa_key.curve.oid)) seq = Sequence() seq.setComponentByPosition(0, alg_id) seq.setComponentByPosition(1, X509EdDSASubjectPublicKey.encode(eddsa_key)) encoded = encoder.encode(seq) return X509EdDSAPublicKey.transport_encode(encoded, **kwargs)
def encodeLoginData(key, data): iv = secrets.token_bytes(8) des = DES3.new(key, DES3.MODE_CBC, iv) ciphertext = des.encrypt(PKCS7pad(data.encode())) asn1data = Sequence() asn1data[0] = OctetString(MAGIC1) asn1data[1] = Sequence() asn1data[1][0] = ObjectIdentifier(MAGIC2) asn1data[1][1] = OctetString(iv) asn1data[2] = OctetString(ciphertext) return b64encode(der_encode(asn1data)).decode()
def tbscert_without_sctlist(tbscert): '''Return pyasn1_modules.rfc2580.TBSCertificate instance `cert_pyasn1` without sctlist extension (OID 1.3.6.1.4.1.11129.2.4.2). ''' sctlist_oid = ObjectIdentifier(value='1.3.6.1.4.1.11129.2.4.2') extensions = tbscert['extensions'] without_sctlist = extensions.subtype() for extension in extensions: if extension['extnID'] != sctlist_oid: without_sctlist.append(extension) copy = copy_pyasn1_instance(tbscert) copy['extensions'] = without_sctlist return copy
class AlgorithmIdentifier(Sequence): """ Define an AlgorithmIdentifier. AlgorithmIdentifier is a custom ASN1 sequence type containing an algortihm OID and any optional parameters. In this case the parameters are always null. """ componentType = NamedTypes( NamedType("algorithm", ObjectIdentifier()), NamedType("parameters", Null()), )
def __new__(cls, oid, curve=None): # preprocessing stage for enum members: # - set enum_member.value to ObjectIdentifier(oid) # - if curve is not None and curve.name is in ec._CURVE_TYPES, set enum_member.curve to curve # - otherwise, set enum_member.curve to None obj = object.__new__(cls) obj._value_ = ObjectIdentifier(oid) obj.curve = None if curve is not None and curve.name in ec._CURVE_TYPES: obj.curve = curve return obj
class RingSignatureSchema(Sequence): """An ASN.1 schema for ring signatures. Ring signatures are identified with an object ID following Recommendation ITU-T X.667. The UUID4 used is 3b5e61af-c4ec-496e-95e9-4b64bccdc809. """ componentType = NamedTypes( NamedType("algorithm", ObjectIdentifier(value=_OBJECT_ID)), NamedType("key_image", OctetString()), NamedType("public_keys", SequenceOf(componentType=OctetString())), NamedType("c", SequenceOf(componentType=OctetString())), NamedType("r", SequenceOf(componentType=OctetString())), )
def encode(rsa_key: object, **kwargs): seq = Sequence() seq.setComponentByPosition( 0, ObjectIdentifier([1, 2, 840, 113549, 1, 1, 1])) seq.setComponentByPosition(1, Null()) param_bs = X509RSASubjectPublicKey.encode(rsa_key) top_seq = Sequence() top_seq.setComponentByPosition(0, seq) top_seq.setComponentByPosition(1, param_bs) encoded = encoder.encode(top_seq) return X509RSAPublicKey.transport_encode(encoded, **kwargs)
def declared_hostinfo(monkeypatch): data = [ [ObjectName('.1.3.6.1.2.1.1.1.0'), OctetString('Cisco Adaptive Security Appliance Version 9.3(2)2')], [ObjectName('.1.3.6.1.2.1.1.2.0'), ObjectIdentifier('1.3.6.1.4.1.9.1.2114')], [ObjectName('.1.3.6.1.2.1.1.3.0'), OctetString('replace with uptime')], [ObjectName('.1.3.6.1.2.1.1.4.0'), OctetString('Networklore')], [ObjectName('.1.3.6.1.2.1.1.6.0'), OctetString('Westeros')], ] return GetCmd(monkeypatch, return_value=data)
def encode(rsa_key: object, **kwargs): alg_id = Sequence() alg_id.setComponentByPosition(0, ObjectIdentifier([1, 2, 840, 113549, 1, 1, 1])) alg_id.setComponentByPosition(1, Null()) param_oct = OctetString(PKCS1RSAPrivateKey.encode(rsa_key, encode_pem=False)) top_seq = Sequence() top_seq.setComponentByPosition(0, Integer(0)) top_seq.setComponentByPosition(1, alg_id) top_seq.setComponentByPosition(2, param_oct) encoded = encoder.encode(top_seq) encoded = PKCS8RSAPrivateKey.transport_encode(encoded, **kwargs) return encoded
class ECPrivateKey(Sequence): componentType = NamedTypes( NamedType( "version", Integer(namedValues=NamedValues(("ecPrivkeyVer1", 1))).subtype( subtypeSpec=Integer.subtypeSpec + SingleValueConstraint(1))), NamedType("privateKey", OctetString()), OptionalNamedType( "parameters", ObjectIdentifier().subtype( explicitTag=Tag(tagClassContext, tagFormatSimple, 0))), OptionalNamedType( "publicKey", BitString().subtype( explicitTag=Tag(tagClassContext, tagFormatSimple, 1))))
def encode(ecdsa_key: object, **kwargs): curve_seq = [ ObjectIdentifier([1, 2, 840, 10045, 2, 1]), X509ECDSAParams.encode(ecdsa_key) ] encoded = SequenceOf() encoded.extend(curve_seq) top_seq = Sequence() top_seq.setComponentByPosition(0, encoded) top_seq.setComponentByPosition( 1, X509ECDSASubjectPublicKey.encode(ecdsa_key)) encoded = encoder.encode(top_seq) return X509ECDSAPublicKey.transport_encode(encoded, **kwargs)
def encode(dsa_key: object, **kwargs): dsa_params = X509DSAParams.encode(dsa_key) seq = Sequence() seq.setComponentByPosition(0, ObjectIdentifier([1, 2, 840, 10040, 4, 1])) seq.setComponentByPosition(1, dsa_params) y_bits = X509DSASubjectPublicKey.encode(dsa_key) top_seq = Sequence() top_seq.setComponentByPosition(0, seq) top_seq.setComponentByPosition(1, y_bits) encoded = encoder.encode(top_seq) return X509DSAPublicKey.transport_encode(encoded, **kwargs)
def encode(dh_key: object, **kwargs): dh_params = X509DiffieHellmanParams.encode(dh_key) seq = Sequence() seq.setComponentByPosition( 0, ObjectIdentifier([1, 2, 840, 113549, 1, 3, 1])) seq.setComponentByPosition(1, dh_params) y_bits = X509DiffieHellmanSubjectPublicKey.encode(dh_key) top_seq = Sequence() top_seq.setComponentByPosition(0, seq) top_seq.setComponentByPosition(1, y_bits) encoded = encoder.encode(top_seq) return X509DiffieHellmanPublicKey.transport_encode(encoded, **kwargs)
def encode(eddsa_key: object, **kwargs): alg_id = SequenceOf() alg_id.setComponentByPosition(0, ObjectIdentifier(eddsa_key.curve.oid)) zero_fill = math.ceil(eddsa_key.d.int().bit_length() / 8) priv_key = OctetString( encoder.encode( OctetString(Bytes.wrap(eddsa_key.d).zfill(zero_fill)))) top_seq = Sequence() top_seq.setComponentByPosition(0, Integer(0)) top_seq.setComponentByPosition(1, alg_id) top_seq.setComponentByPosition(2, priv_key) encoded = encoder.encode(top_seq) encoded = PKCS8EdDSAPrivateKey.transport_encode(encoded, **kwargs) return encoded