def __init__(self, host, protocol,community=None, secname='test-agent', user=None, authkey=None, privkey=None, timeout=None, port=161, authProtocol='md5'): errortext = self._validate_input(host, protocol, community, secname, user, authkey, privkey,timeout, port, authProtocol) if errortext: raise SnmpBadArgumentError(errortext) # for oid conversions self.oid_converter = ObjectIdentifier() self.protocol = protocol self.timeout = timeout self.target = cmdgen.UdpTransportTarget((host, port)) if protocol is 1: self.authentication = cmdgen.CommunityData(secname, community, 0) elif protocol is 2: self.authentication = cmdgen.CommunityData(secname, community) elif protocol is 3: if privkey: privprot = cmdgen.usmD else: privprot = cmdgen.usmNoPrivProtocol if authkey: if authProtocol == 'md5': authprot = cmdgen.usmHMACMD5AuthProtocol else: authprot = cmdgen.usmHMACSHAAuthProtocol else: authprot = cmdgen.usmNoAuthProtocol if privkey: privprot = cmdgen.usmDESPrivProtocol else: privprot = cmdgen.usmNoPrivProtocol self.authentication = cmdgen.UsmUserData(user, authkey, privkey, authprot, privprot) self.snmpclient = cmdgen.CommandGenerator()
def get_table(self, oid): '''This method accepts the oid of the table ENTRY and returns a dictionary containing the table. Currently only works with snmpv2 and3''' # explanation http://dartware.com/support/faqs/snmpfaqs.html#table table = {} parent = self.oid_converter.prettyIn(oid) parent = ObjectIdentifier(parent) if self.protocol in (2,3): raw = self.get(oid, bulk=True) for child in raw: if not parent.isPrefixOf(child): continue nrs = child.prettyPrint().split('.') rij = int(nrs.pop()) kolom = int(nrs.pop()) try: table[kolom][rij]= raw[child] except: table[kolom] = {} table[kolom][rij]= raw[child] return table elif protocol is 1: # TODO implement with SNMPVv1 getnext pass
class SnmpClient(object): '''Simple Snmpv1/2/3 Client class Required arguments * host: string - snmp agent hostname * protocol: integer - snmp protocol version 1,2 or 3 Arguments that might be required depending on the protocol version: * community: string - snmpv1 community string * secname string - snmpv1 security name * user: string - snmpv3 security user, default None * authkey: string - snmpv3 authentication key, default None * authProtocol: string - snmpv3 authentication protocol can be 'md5' or 'sha', default 'md5' * privkey: string - snmpv3 encrytion key, default None Other arguments: * port integer - default 163 The privacy protocol used is DES (only protocol implemented) Supplied methods * get * get_table SNMPv1 example: s = SnmpClient('netappa1', 1, community='password') SNMPv3 authNoPriv example: s = SnmpClient('jay1', 3, user='******', authkey='password') s.get('1.3.6.1.2.1.1.1.0')''' def __init__(self, host, protocol,community=None, secname='test-agent', user=None, authkey=None, privkey=None, timeout=None, port=161, authProtocol='md5'): errortext = self._validate_input(host, protocol, community, secname, user, authkey, privkey,timeout, port, authProtocol) if errortext: raise SnmpBadArgumentError(errortext) # for oid conversions self.oid_converter = ObjectIdentifier() self.protocol = protocol self.timeout = timeout self.target = cmdgen.UdpTransportTarget((host, port)) if protocol is 1: self.authentication = cmdgen.CommunityData(secname, community, 0) elif protocol is 2: self.authentication = cmdgen.CommunityData(secname, community) elif protocol is 3: if privkey: privprot = cmdgen.usmD else: privprot = cmdgen.usmNoPrivProtocol if authkey: if authProtocol == 'md5': authprot = cmdgen.usmHMACMD5AuthProtocol else: authprot = cmdgen.usmHMACSHAAuthProtocol else: authprot = cmdgen.usmNoAuthProtocol if privkey: privprot = cmdgen.usmDESPrivProtocol else: privprot = cmdgen.usmNoPrivProtocol self.authentication = cmdgen.UsmUserData(user, authkey, privkey, authprot, privprot) self.snmpclient = cmdgen.CommandGenerator() def _validate_input(self, host,protocol, community, secname, user, authkey, privkey, timeout, port, authProtocol): '''Validates arguments, returns False if valid, else error message''' if not protocol in (1,2,3): return 'unknown protocol version' if not type(port) is int: return 'port must be an integer' if (port < 0) or (port >= 2**16): return 'port must be >= 0 and < 2^16' if protocol in (1,2): if not community: return 'community is a required argument for snmpv1/2' if protocol is 3: if not user: return 'user is a required argument for snmpv3' if authkey: if not authProtocol in ('md5', 'sha'): return 'unknown authentication protocol' return False def get(self, oid, bulk=False): '''Get the value for the oid, raises SnmpError Return value is always a string''' # Dotted string -> tuple of numerics OID conversion try: oid = self.oid_converter.prettyIn(oid) except PyAsn1Error: raise SnmpBadArgumentError('Invalid OID format') try: if bulk: result = self.snmpclient.bulkCmd(self.authentication, self.target, 0, 25, oid) else: result = self.snmpclient.getCmd(self.authentication, self.target, oid) except NoSuchObjectError: raise SnmpNoInstanceError errorIndication, errorStatus, errorIndex, varBinds = result # can't get anything from this SNMP agent: # network or authorization problem if errorIndication: raise SnmpError(errorIndication) else: # problem with this specific OID if errorStatus: raise SnmpError('%s at %s' % (errorStatus, varBinds[int(errorIndex)-1]) ) # no problems, we got the value else: resultdict = {} for row in varBinds: if bulk: [(name, val)] = row resultdict[name]=val return resultdict else: name, val = row if isinstance(val, Null): raise SnmpNoInstanceError("OID doesn't exist") return val def get_table(self, oid): '''This method accepts the oid of the table ENTRY and returns a dictionary containing the table. Currently only works with snmpv2 and3''' # explanation http://dartware.com/support/faqs/snmpfaqs.html#table table = {} parent = self.oid_converter.prettyIn(oid) parent = ObjectIdentifier(parent) if self.protocol in (2,3): raw = self.get(oid, bulk=True) for child in raw: if not parent.isPrefixOf(child): continue nrs = child.prettyPrint().split('.') rij = int(nrs.pop()) kolom = int(nrs.pop()) try: table[kolom][rij]= raw[child] except: table[kolom] = {} table[kolom][rij]= raw[child] return table elif protocol is 1: # TODO implement with SNMPVv1 getnext pass def get_dict(self, oid_dict): '''Accepts a dictionary like this: {'oidname1': '.1.2.3.4.5', 'oidname2':'.1.2.3.4.6'} and replaces the oid strings with their values, if they could be retrieved. Only the retrieved oid's will be returned Returns False if an SNMP error occured (other than not being able to retrieve a value)''' results = {} for name in oid_dict: try: x = self.get(oid_dict[name]) except SnmpNoInstanceError: continue except: return False else: results[name] = x return results
) # workaround https://github.com/trevp/tlslite/issues/15 tlslite.utils.cryptomath.pycryptoLoaded = False from pyasn1.codec.der import decoder, encoder from pyasn1.type.univ import Any, ObjectIdentifier, OctetString from pyasn1.type.char import BMPString, IA5String, UTF8String from pyasn1.type.useful import GeneralizedTime from pyasn1_modules.rfc2459 import (Certificate, DirectoryString, SubjectAltName, GeneralNames, GeneralName) from pyasn1_modules.rfc2459 import id_ce_subjectAltName as SUBJECT_ALT_NAME from pyasn1_modules.rfc2459 import id_at_commonName as COMMON_NAME from pyasn1_modules.rfc2459 import id_at_organizationalUnitName as OU_NAME from pyasn1_modules.rfc2459 import id_ce_basicConstraints, BasicConstraints XMPP_ADDR = ObjectIdentifier('1.3.6.1.5.5.7.8.5') SRV_NAME = ObjectIdentifier('1.3.6.1.5.5.7.8.7') ALGO_RSA_SHA1 = ObjectIdentifier('1.2.840.113549.1.1.5') ALGO_RSA_SHA256 = ObjectIdentifier('1.2.840.113549.1.1.11') class CertificateError(Exception): pass def decode_str(data): encoding = 'utf-16-be' if isinstance(data, BMPString) else 'utf-8' return bytes(data).decode(encoding) class X509(tlslite.X509):
# Make a call to strptime before starting threads to # prevent thread safety issues. datetime.strptime('1970-01-01 12:00:00', "%Y-%m-%d %H:%M:%S") try: from pyasn1.codec.der import decoder, encoder from pyasn1.type.univ import Any, ObjectIdentifier, OctetString from pyasn1.type.char import BMPString, IA5String, UTF8String from pyasn1.type.useful import GeneralizedTime from pyasn1_modules.rfc2459 import (Certificate, DirectoryString, SubjectAltName, GeneralNames, GeneralName) from pyasn1_modules.rfc2459 import id_ce_subjectAltName as SUBJECT_ALT_NAME from pyasn1_modules.rfc2459 import id_at_commonName as COMMON_NAME XMPP_ADDR = ObjectIdentifier('1.3.6.1.5.5.7.8.5') SRV_NAME = ObjectIdentifier('1.3.6.1.5.5.7.8.7') HAVE_PYASN1 = True except ImportError: HAVE_PYASN1 = False log = logging.getLogger(__name__) class CertificateError(Exception): pass def decode_str(data): encoding = 'utf-16-be' if isinstance(data, BMPString) else 'utf-8'
return bytes(data).decode("utf-8") if HAVE_PYASN1: from pyasn1_modules.rfc2459 import Certificate, DirectoryString, MAX, Name from pyasn1_modules import pem from pyasn1.codec.der import decoder as der_decoder from pyasn1.type.char import BMPString, IA5String, UTF8String from pyasn1.type.univ import Sequence, SequenceOf, Choice from pyasn1.type.univ import Any, ObjectIdentifier, OctetString from pyasn1.type.namedtype import NamedTypes, NamedType from pyasn1.type.useful import GeneralizedTime from pyasn1.type.constraint import ValueSizeConstraint from pyasn1.type import tag XMPPADDR_OID = ObjectIdentifier('1.3.6.1.5.5.7.8.5') SRVNAME_OID = ObjectIdentifier('1.3.6.1.5.5.7.8.7') SUBJECT_ALT_NAME_OID = ObjectIdentifier('2.5.29.17') 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)))) class GeneralName(Choice): # pylint: disable=C0111,R0903 componentType = NamedTypes(
def encode(ecdsa_key): return ObjectIdentifier( ber_decoder.decode(b'\x06' + bytes([len(ecdsa_key.G.curve.oid)]) + ecdsa_key.G.curve.oid)[0].asTuple())
) print("It can be compiled as follows : ") print("1. Build the BearSSL library") print( "2. Compile and link the helper binary with the following command : ") print( "gcc DilithiumCertEditor_dilithium_sign.c -Iinc/ -Lbuild/ -l:libbearssl.a -o DilithiumCertEditor_dilithium_sign" ) print( "NB : The command assumes the current directory to be the root of the BearSSL git structure." ) exit(-1) # change TBS signature algorithm if an algorithm is given if args['sign_algorithm']: cert["tbsCertificate"]["signature"]["algorithm"] = ObjectIdentifier( DilithiumSignAlgoToOID[args['sign_algorithm']]) # change TBS public key type cert["tbsCertificate"]["subjectPublicKeyInfo"]["algorithm"][ "algorithm"] = ObjectIdentifier(DilithiumOIDKeyDict[args["pub_key_type"]]) # Force Null TBS public key params (in case of EC certificate mainly) cert["tbsCertificate"]["subjectPublicKeyInfo"]["algorithm"][ "parameters"] = Null("") # Load the raw DER Dilithium public key from the PEM file dilithium_substrate = b'' for line in open(args['pub_key'], 'r').readlines(): if not line.startswith('-'): dilithium_substrate += line.rstrip().encode() dilithium_public_key = decoder.decode(
Integer32, IpAddress, ObjectName, OctetString, TimeTicks, Unsigned32, ) data = [] data.append([ObjectName('.1.'), Counter32('100'), 100]) data.append([ObjectName('.1.'), Counter64('100'), 100]) data.append([ObjectName('.1.'), Gauge32('100'), 100]) data.append([ObjectName('.1.'), Integer('100'), 100]) data.append([ObjectName('.1.'), Integer32('100'), 100]) data.append([ObjectName('.1.'), IpAddress('192.168.1.1'), '192.168.1.1']) data.append([ObjectName('.1.'), ObjectIdentifier('1'), '1']) data.append([ObjectName('.1.'), OctetString('my_string'), 'my_string']) data.append([ObjectName('.1.'), Unsigned32('100'), 100]) @pytest.fixture(scope='function', params=data) def query_data(monkeypatch, request): snmp_data = [[request.param[0], request.param[1]]] return GetCmdValues(monkeypatch, return_value=snmp_data, params=request.param) def test_return_value_types(query_data): dev = SnmpHandler(host='1.1.1.1', version='2c', community='public') varbinds = dev.get('1')
:raises service_identity.CertificateError: If the certificate chain of *connection* contains a certificate that contains invalid/unexpected data. :returns: ``None`` .. versionadded:: 18.1.0 """ verify_service_identity( cert_patterns=extract_ids(connection.get_peer_certificate()), obligatory_ids=[IPAddress_ID(ip_address)], optional_ids=[], ) ID_ON_DNS_SRV = ObjectIdentifier("1.3.6.1.5.5.7.8.7") # id_on_dnsSRV def extract_ids(cert): """ Extract all valid IDs from a certificate for service verification. If *cert* doesn't contain any identifiers, the ``CN``s are used as DNS-IDs as fallback. :param OpenSSL.SSL.X509 cert: The certificate to be dissected. :return: List of IDs. """ ids = [] for i in six.moves.range(cert.get_extension_count()):
class NPKIPlainPrivateKeyInfo(Sequence): componentType = NamedTypes(NamedType('oid', ObjectIdentifier()), NamedType('null', Null()))
class NPKIPrivateKeyRandomNumber(Sequence): componentType = NamedTypes( NamedType('oid', ObjectIdentifier()), NamedType('rand_set', NPKIPrivateKeyRandomNumberSet()), )
class AlgorithmIdentifier(Sequence): componentType = NamedTypes( NamedType('oid', ObjectIdentifier()), NamedType('data', AlgorithmIdentifierData()), )
#!/usr/bin/env python3 import argparse import os from pyasn1_modules import pem, rfc2459 from pyasn1.type.univ import ObjectIdentifier from Crypto.Hash import SHA as SHA1, SHA256, SHA384, SHA512 from pyasn1_modules.rfc2437 import RSAPublicKey, sha1WithRSAEncryption from pyasn1.codec.der import decoder as der_decoder, encoder as der_encoder from pyasn1_modules.rfc2459 import id_at_commonName as OID_COMMON_NAME, id_ce_keyUsage as OID_EXT_KEY_USAGE, KeyUsage rsa_signing_algorithms = { sha1WithRSAEncryption: SHA1, # defined in RFC 2437 (obsoleted by RFC 3447) ObjectIdentifier('1.2.840.113549.1.1.11'): SHA256, # defined in RFC 3447 ObjectIdentifier('1.2.840.113549.1.1.12'): SHA384, # defined in RFC 3447 ObjectIdentifier('1.2.840.113549.1.1.13'): SHA512 } # defined in RFC 3447 def find_key_usage(extensions): return next(e['extnValue'] for e in extensions if e['extnID'] == OID_EXT_KEY_USAGE) def common_name(name): name = name.getComponent() for relative_distinguished_name in name: for attribute_type_and_value in relative_distinguished_name: oid = attribute_type_and_value['type'] if oid == OID_COMMON_NAME: value = attribute_type_and_value['value'] ds, rest = der_decoder.decode(value, asn1Spec=rfc2459.DirectoryString())
def pkcs7_sign_msg(self, msg): """WIP: PKCS#7 sign with certificate Sign and encapsulize message """ 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)