示例#1
0
    def initialize_snmp(self, snmp_parameters):
        """Create snmp, using provided version user details or community name

        :param SNMPParameters snmp_parameters: snmp parameters

        """

        self.logger.info('QualiSnmp Creating SNMP Handler')
        ip = snmp_parameters.ip
        if ':' in ip:
            ip = ip.split(':')[0]
        self.target = cmdgen.UdpTransportTarget((ip, snmp_parameters.port))
        if isinstance(snmp_parameters, SNMPV3Parameters):
            snmp_v3_param = snmp_parameters
            """:type: SNMPV3Parameters"""
            self.security = UsmUserData(
                userName=snmp_v3_param.snmp_user,
                authKey=snmp_v3_param.snmp_password,
                privKey=snmp_v3_param.snmp_private_key,
                authProtocol=snmp_v3_param.auth_protocol,
                privProtocol=snmp_v3_param.private_key_protocol)
            self.logger.info('Snmp v3 handler created')
        else:
            if isinstance(snmp_parameters, SNMPV2ReadParameters):
                self.is_read_only = True
            snmp_v2_param = snmp_parameters
            """:type: SNMPV2Parameters"""
            self.security = cmdgen.CommunityData(snmp_v2_param.snmp_community)
            self.logger.info('Snmp v2 handler created')
        self._test_snmp_agent()
def get_snmp_with_auth(template_oids, ip, port, user_name, authen_protocol,
                       authen_password, priv_protocol, priv_password, timeout,
                       retries):
    """
    :param template_oids:
    :param ip:
    :param port:
    :param user_name:
    :param authen_protocol:
    :param authen_password:
    :param priv_protocol:
    :param priv_password:
    :param timeout:
    :param retries:
    :return:
            errorIndication, errorStatus, errorIndex, varBinds
    """
    return next(
        getCmd(
            SnmpEngine(),
            UsmUserData(
                user_name,
                authKey=process_password.decrypt_password(
                    empty_to_none(authen_password)),
                privKey=process_password.decrypt_password(
                    empty_to_none(priv_password)),
                authProtocol=AUTH_PROTOCOL[empty_to_none(authen_protocol)],
                privProtocol=PRIV_PROTOCOL[empty_to_none(priv_protocol)]),
            UdpTransportTarget((ip, port), timeout=timeout, retries=retries),
            ContextData(), *template_oids))
示例#3
0
def get_security_engine_id(logger, ir: InventoryRecord,
                           snmpEngine: SnmpEngine):
    observerContext: Dict[Any, Any] = {}

    transportTarget = UdpTransportTarget((ir.address, ir.port),
                                         timeout=UDP_CONNECTION_TIMEOUT)

    # Register a callback to be invoked at specified execution point of
    # SNMP Engine and passed local variables at execution point's local scope
    snmpEngine.observer.registerObserver(
        lambda e, p, v, c: c.update(securityEngineId=v["securityEngineId"]),
        "rfc3412.prepareDataElements:internal",
        cbCtx=observerContext,
    )

    # Send probe SNMP request with invalid credentials
    authData = UsmUserData("non-existing-user")

    errorIndication, errorStatus, errorIndex, varBinds = next(
        getCmd(
            snmpEngine,
            authData,
            transportTarget,
            ContextData(),
            ObjectType(ObjectIdentity("SNMPv2-MIB", "sysDescr", 0)),
        ))

    # See if our SNMP engine received REPORT PDU containing securityEngineId
    securityEngineId = fetch_security_engine_id(observerContext,
                                                errorIndication)
    logger.debug(f"securityEngineId={securityEngineId}")
    return securityEngineId
示例#4
0
class QualiSnmp(object):
    """ A wrapper class around PySNMP.

    :todo: use pysnmp.hlapi, do we really need to import symbols? see
        pysnmp.sourceforge.net/examples/hlapi/asyncore/sync/manager/cmdgen/table-operations.html
    """

    var_binds = ()
    """ raw output from PySNMP command. """

    def __init__(self, ip, port=161, community='private', v3_user=None):
        """ Initialize SNMP environment .

        :param ip: device IP.
        :param port: device SNMP port.
        :param community: device community string.
        """
        super(QualiSnmp, self).__init__()

        self.target = cmdgen.UdpTransportTarget((ip, port))
		mib_builder.setMibSources(mibPath)
        if v3_user:
            v3_user_data = v3_user.copy()
            if 'authProtocol' not in v3_user_data:
                v3_user_data['authProtocol'] = usmHMACSHAAuthProtocol
            if 'privProtocol' not in v3_user_data:
                v3_user_data['privProtocol'] = usmDESPrivProtocol
            self.security = UsmUserData(**v3_user_data)
        else:
            self.security = cmdgen.CommunityData(community)
示例#5
0
 def __init__(self, host_ip, username, auth_key, priv_key):
     super(V3Endpoint, self).__init__(host_ip, 3)
     self.usm_user = UsmUserData(userName=username,
                                 authKey=auth_key,
                                 privKey=priv_key,
                                 authProtocol=usmHMACMD5AuthProtocol,
                                 privProtocol=usmDESPrivProtocol
                                 )
示例#6
0
 def get_auth_data(self):
     """ Returns the authentication data that is used in the SNMP
     command generator """
     if self.version != 3:
         return CommunityData(self.community)
     return UsmUserData(
         self.community, self.auth_passwd, self.priv_passwd,
         AUTH_PROTOCOLS.get(self.auth_type, AUTH_PROTOCOLS[AUTH_NONE]),
         PRIV_PROTOCOLS.get(self.priv_type, PRIV_PROTOCOLS[PRIV_NONE]))
示例#7
0
def getAuthV3(logger, ir: InventoryRecord,
              snmpEngine: SnmpEngine) -> UsmUserData:
    location = os.path.join("secrets/snmpv3", ir.secret)  # type: ignore
    if os.path.exists(location):
        userName = get_secret_value(location, "userName", required=True)

        authKey = get_secret_value(location, "authKey", required=False)
        privKey = get_secret_value(location, "privKey", required=False)

        authProtocol = get_secret_value(location,
                                        "authProtocol",
                                        required=False)
        authProtocol = AuthProtocolMap.get(authProtocol.upper(), "NONE")

        privProtocol = get_secret_value(location,
                                        "privProtocol",
                                        required=False,
                                        default="NONE")
        privProtocol = PrivProtocolMap.get(privProtocol.upper(), "NONE")

        authKeyType = int(
            get_secret_value(location,
                             "authKeyType",
                             required=False,
                             default="0"))

        privKeyType = int(
            get_secret_value(location,
                             "privKeyType",
                             required=False,
                             default="0"))
        if (isinstance(ir.securityEngine, str) and ir.securityEngine != ""
                and not ir.securityEngine.isdigit()):
            securityEngineId = ir.securityEngine
            logger.debug(f"Security eng from profile {ir.securityEngine}")
        else:
            securityEngineId = get_security_engine_id(logger, ir, snmpEngine)
            logger.debug(f"Security eng dynamic {securityEngineId}")

        securityName = None
        logger.debug(
            f"{userName},authKey={authKey},privKey={privKey},authProtocol={authProtocol},privProtocol={privProtocol},securityEngineId={securityEngineId},securityName={securityName},authKeyType={authKeyType},privKeyType={privKeyType}"
        )
        return UsmUserData(
            userName,
            authKey=authKey,
            privKey=privKey,
            authProtocol=authProtocol,
            privProtocol=privProtocol,
            securityEngineId=securityEngineId,
            securityName=securityName,
            authKeyType=authKeyType,
            privKeyType=privKeyType,
        )

    else:
        raise Exception(f"invalid username from secret {ir.secret}")
示例#8
0
 def get_auth(self):
     '''
     get auth by snmp version
     '''
     auth = None
     if self.version == self.SNMP_VERSION_2C:
         auth = CommunityData(self.community)
     elif self.version == self.SNMP_VERSION_3:
         auth = UsmUserData(self.user_name,
                            authKey=self.auth_key, privKey=self.priv_key)
     return auth
示例#9
0
文件: snmp.py 项目: SrijaGupta/file
    def create_community_data(self, **kwargs):
        """
            :param version: SNMP Version. Default to 2
            :param user: UserID
            :param password: Password
            :return:
        """
        t.log("DEBUG", "Entering 'create_community_data'\n"+__file__)
        version = kwargs.get('version', self.version)
        user = kwargs.get('user', self.user)
        auth_type = kwargs.get('auth_type', self.auth_type)
        auth_pass = kwargs.get('auth_pass', self.auth_pass)
        priv_type = kwargs.get('priv_type', self.priv_type)
        priv_pass = kwargs.get('priv_pass', self.priv_pass)
        community = kwargs.get('community', self.community)

        valid_auth_type = ['usmHMACMD5AuthProtocol', 'usmHMACSHAAuthProtocol']
        valid_priv_type = ['usmDESPrivProtocol', 'usm3DESEDEPrivProtocol',
                           'usmAesCfb128Protocol', 'usmAesCfb192Protocol',
                           'usmAesCfb256Protocol']

        if version == 1:
            return_value = CommunityData(community, mpModel=0)
        elif version == 2:
            return_value = CommunityData(community)
        elif version == 3:
            if priv_type == 'usmNoPrivProtocol' and \
                    auth_pass in valid_auth_type:
                return_value = UsmUserData(user, auth_pass,\
                                   authProtocol=eval(auth_type))
            elif auth_type in valid_auth_type and priv_type in valid_priv_type:
                return_value = UsmUserData(user, auth_pass, priv_pass, \
                                   authProtocol=eval(auth_type),\
                                   privProtocol=eval(priv_type))
            else:
                return_value = UsmUserData(user)
        else:
            t.log(level="DEBUG", message="Invalid Version")
            raise Exception("Invalid Version")
        t.log(level="DEBUG", message="Exiting 'create_community_data' with return value/code :\n"+str(return_value))
        return return_value
示例#10
0
def prepare_authdata(config, snmpversion="2c"):
    """Prapare authentication data object for various SNMP versions"""
    # SNMP v1 and v2c
    if config["community"]:
        if snmpversion == "2c":
            model = 1
        elif snmpversion == "1":
            model = 0
        authdata = CommunityData(config["community"], mpModel=model)
    # SNMP v3
    else:
        priv_protocol, auth_protocol = set_snmp_security_protocols(config)

        authdata = UsmUserData(
            config["user"],
            authKey=config["authpassword"],
            privKey=config["privpassword"],
            authProtocol=auth_protocol,
            privProtocol=priv_protocol,
        )
    return authdata
示例#11
0
    def port_interaction(self, command, port_number):
        if command == "on":
            set_bit = self.onsetting
        elif command == "off":
            set_bit = self.offsetting
        else:
            raise UnknownCommandException("Unknown command %s." % (command))

        transport = UdpTransportTarget((self.hostname, 161))
        objecttype = ObjectType(
            ObjectIdentity(self.mib, self.controlpoint,
                           port_number).addAsn1MibSource(
                               'http://mibs.snmplabs.com/asn1/@mib@'),
            int(set_bit))

        if self.version == 'snmpv3':
            if not self.username:
                raise FailedRequestException("No username set for snmpv3")
            userdata = UsmUserData(self.username, self.authpass, self.privpass)
            errorIndication, errorStatus, errorIndex, varBinds = next(
                setCmd(SnmpEngine(), userdata, transport, ContextData(),
                       objecttype))
        elif self.version == 'snmpv1':
            if not self.community:
                raise FailedRequestException("No community set for snmpv1")
            errorIndication, errorStatus, errorIndex, varBinds = next(
                setCmd(SnmpEngine(), CommunityData(self.community), transport,
                       ContextData(), objecttype))
        else:
            raise FailedRequestException("Unknown snmp version")

        if errorIndication:
            raise FailedRequestException(errorIndication)
        elif errorStatus:
            raise FailedRequestException(errorStatus)
        else:
            for varBind in varBinds:
                log.debug(' = '.join([x.prettyPrint() for x in varBind]))
            return True
示例#12
0
    def initialize_snmp(self, ip_address, port, snmp_version, snmp_community,
                        snmp_user, snmp_password, snmp_private_key,
                        auth_protocol, private_key_protocol):
        """Create snmp, using provided version user details or community name

        :param ip_address: target device ip address
        :param port: snmp port
        :param snmp_version: snmp version, i.e. v2c, v3, etc.
        :param snmp_community: snmp community name, used to instantiate snmp agent version 2
        :param snmp_user: snmp user name, used to instantiate snmp agent version 3
        :param snmp_password: snmp password, used to instantiate snmp agent version 3
        :param snmp_private_key: snmp private key, used to instantiate snmp agent version 3
        :param auth_protocol: authentication protocol, used to instantiate snmp agent version 3,
                i.e. usmNoAuthProtocol, usmHMACMD5AuthProtocol, etc. objects
        :param private_key_protocol: private key protocol, used to instantiate snmp agent version 3,
                i.e. usmNoPrivProtocol, usm3DESEDEPrivProtocol, usmAesCfb128Protocol, etc. objects
        """

        self._logger.info('QualiSnmp Creating SNMP Handler')
        ip = ip_address
        if ':' in ip_address:
            ip = ip_address.split(':')[0]
        self.target = cmdgen.UdpTransportTarget((ip, port))
        # self._logger.debug('incoming params: ip: {0} community:{1}, user: {2}, password:{3}, private_key: {4}'.format(
        #    ip, snmp_community, snmp_user, snmp_password, snmp_private_key))
        if '3' in snmp_version:
            self.security = UsmUserData(userName=snmp_user,
                                        authKey=snmp_password,
                                        privKey=snmp_private_key,
                                        authProtocol=auth_protocol,
                                        privProtocol=private_key_protocol)
            self._logger.info('Snmp v3 handler created')
        else:
            if not snmp_community or snmp_community == '':
                raise Exception('QualiSnmp',
                                'Snmp parameters is empty or invalid')
            self.security = cmdgen.CommunityData(snmp_community)
            self._logger.info('Snmp v2 handler created')
        self._test_snmp_agent()
示例#13
0
    def sendTrap(self, trap):
        trap_oid = trap['trap_oid']

        txAddress = self.args['--ipv6-host']
        txPort = self.args['--port']
        userData = UsmUserData('user-sha-aes128',
                               'authkey1',
                               'privkey1',
                               authProtocol=usmHMACSHAAuthProtocol,
                               privProtocol=usmAesCfb128Protocol)

        log.info("Sending SNMP Trap", address=txAddress, port=txPort)
        log.info("  Notification",
                 name=self.smd.getNameByNumOid(trap_oid),
                 oid=trap_oid)
        for var_bind in trap['var_binds']:
            var_oid = var_bind[0]
            var_val = var_bind[1]
            log.info("  with Object",
                     name=self.smd.getNameByNumOid(var_oid),
                     oid=var_oid,
                     type=type(var_val))

        trapOid = trap['trap_oid']
        txVarBinds = trap['var_binds']
        errorIndicationTx, errorStatusTx, errorIndexTx, varBindsTx = next(
            sendNotification(
                SnmpEngine(OctetString(hexValue='8000000001020304')), userData,
                Udp6TransportTarget((txAddress, txPort)), ContextData(),
                'trap',
                NotificationType(
                    ObjectIdentity(trapOid)).addVarBinds(*txVarBinds)))
        if errorIndicationTx:
            print(errorIndicationTx)
        else:
            for varBindTx in varBindsTx:
                print(' = '.join([x.prettyPrint() for x in varBindTx]))
示例#14
0
    def SNMP_set_state(self, _MIB: str, _OID: str, _PORT: int, _STATE: int):
        l = []
        errorIndication, errorStatus, errorIndex, varBinds = next(
            setCmd(
                SnmpEngine(),
                UsmUserData(self.snmp_username, authKey=self.snmp_password),
                UdpTransportTarget((self.ip, self.snmp_port)), ContextData(),
                ObjectType(
                    ObjectIdentity('LUXL-POE-MIB',
                                   'luxlPoeConfigInterfaceParamMode', _PORT),
                    _STATE)))

        if errorIndication:
            self.logger.log(
                "GET_BULK: errorIndicaton | {}".format(errorIndication), 5)
        elif errorStatus:
            self.logger.log(
                "GET_BULK: errorStatus | {} at {}".format(
                    errorStatus.prettyPrint(),
                    errorIndex and varBinds[int(errorIndex) - 1][0] or '?'), 5)
        else:
            for varBind in varBinds:
                l.append(varBind)
        return l
示例#15
0
)

if errorIndication:
    print(errorIndication)
elif errorStatus:
    print('%s at %s' % (errorStatus.prettyPrint(),
                        errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
    for varBind in varBinds:
        print(' = '.join([x.prettyPrint() for x in varBind]))
'''

from pysnmp.hlapi import *
from pysnmp.hlapi import UsmUserData

errorIndication, errorStatus, errorIndex, varBinds = next(
    setCmd(SnmpEngine(),
           UsmUserData('user',authKey='password'),
           UdpTransportTarget(('192.168.61.6', 161)),
           ContextData(),
           ObjectType(ObjectIdentity('LUXL-POE-MIB', 'luxlPoeConfigInterfaceParamMode', 1000001).addAsn1MibSource('file:///Users/michaelhelton/Downloads/LUXL_MIBs_ALL/LUXL-POE-MIB.mib'),2))
)

if errorIndication:
    print(errorIndication)
elif errorStatus:
    print('%s at %s' % (errorStatus.prettyPrint(),
                        errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
    for varBind in varBinds:
        print(' = '.join([x.prettyPrint() for x in varBind]))
def get_bulk_snmp(template_oid,
                  ip,
                  snmp_config_data,
                  timeout=1,
                  retries=0,
                  lexicographicMode=False):
    """[Get bulk Snmp]
    Arguments:
        template_oid {[string]} -- [OID]
        ip {[string]} -- [ip of server(ex: 192.168.88.88)]
        snmp_config_data {[type]} -- [snmp config get from config file]
    Keyword Arguments:
        timeout {int} -- [timeout in seconds] (default: {1})
        retries {int} -- [Maximum number of request retries, 0 retries means just a single request.] (default: {0})
        lexicographicMode {bool} -- [walk SNMP agent’s MIB till the end (if True), 
            otherwise (if False) stop iteration when all response MIB variables leave the scope of initial MIB variables in varBinds] (default: {False})
    Raises:
        KeyError: [snmp_version input wrong format. Not match in map_snmp_version]
        KeyError: [property is not exist in snmp_config_data]
    Returns:
        [generator] -- [result generator data get by snmp]
    """
    try:
        snmp_version = snmp_config_data['snmp_version']
        port = snmp_config_data['port']

        if snmp_version == "v1" or snmp_version == "v2c":
            snmp_community = snmp_config_data['snmp_community']

            snmp_iter = bulkCmd(SnmpEngine(),
                                CommunityData(
                                    snmp_community,
                                    mpModel=map_snmp_version[snmp_version]),
                                UdpTransportTarget((ip, port),
                                                   timeout=timeout,
                                                   retries=retries),
                                ContextData(),
                                0,
                                10,
                                ObjectType(ObjectIdentity(template_oid)),
                                lexicographicMode=lexicographicMode)
        elif snmp_version == "v3":
            user_name = snmp_config_data['user_name']
            auth_key = process_password.decrypt_password(
                empty_to_none(snmp_config_data['authen_password']))
            priv_key = process_password.decrypt_password(
                empty_to_none(snmp_config_data['priv_password']))
            auth_protocol = AUTH_PROTOCOL[empty_to_none(
                snmp_config_data['authen_protocol'])]
            priv_protocol = PRIV_PROTOCOL[empty_to_none(
                snmp_config_data['priv_protocol'])]

            snmp_iter = bulkCmd(SnmpEngine(),
                                UsmUserData(user_name,
                                            authKey=auth_key,
                                            privKey=priv_key,
                                            authProtocol=auth_protocol,
                                            privProtocol=priv_protocol),
                                UdpTransportTarget((ip, port),
                                                   timeout=timeout,
                                                   retries=retries),
                                ContextData(),
                                0,
                                10,
                                ObjectType(ObjectIdentity(template_oid)),
                                lexicographicMode=lexicographicMode)
        else:
            raise KeyError(
                "'{}' wrong format snmp_version".format(snmp_version))
    except KeyError as key_error:
        raise KeyError("Can not find {} in snmp_config_data".format(key_error))
    except Exception as ex:
        raise ex
    return snmp_iter
示例#17
0
文件: test.py 项目: CoYe/qualisnmp
from unittest import TestCase

from pysnmp.hlapi import UsmUserData, usmHMACSHAAuthProtocol, usmDESPrivProtocol

from qualisnmp.quali_snmp import QualiSnmp, load_mib
from qualisnmp.snmp_autoload import AutoLoad

ip = '172.25.10.204'
ro_community = 'public'
rw_community = ''
v3_user = UsmUserData('QUALI', 'Password1', 'Live4lol', usmHMACSHAAuthProtocol,
                      usmDESPrivProtocol)


class SnmpTest(TestCase):
    """ SNMP class tests.

    :todo: test with assert.
    """
    def setUp(self):
        self.snmp = QualiSnmp(ip=ip, community=ro_community)

    def testGet(self):

        values = self.snmp.get(('ENTITY-MIB', 'entPhysicalDescr', 7))
        print values

        values = self.snmp.get('1.3.6.1.2.1.1.4.0', '1.3.6.1.2.1.1.1.0')
        print values

        values = self.snmp.get('1.3.6.1.2.1.1.4', '1.3.6.1.2.1.1.1')
示例#18
0
文件: snmp.py 项目: PyCQA/bandit
from pysnmp.hlapi import CommunityData, UsmUserData

# SHOULD FAIL
a = CommunityData('public', mpModel=0)
# SHOULD FAIL
insecure = UsmUserData("securityName")
# SHOULD FAIL
auth_no_priv = UsmUserData("securityName", "authName")
# SHOULD PASS
less_insecure = UsmUserData("securityName", "authName", "privName")
示例#19
0
from pysnmp.hlapi import UsmUserData
a = UsmUserData('testuser', authKey='authenticationkey')
AUTHKEY = "horse"
a.userName='******'
a.authKey= "horse"
a.privKey= ""
a.authProtocol=(1,3,6,1,6,3,10,1,1,2)
a.privProtocol=(1,3,6,1,6,3,10,1,2,1)
UsmUserData('testuser', authKey='authenticationkey', privKey='encryptionkey')
b = UsmUserData(userName='******', authKey="", privKey=<PRIVKEY>, authProtocol=(1,3,6,1,6,3,10,1,1,2), privProtocol=(1,3,6,1,6,3,10,1,2,2))
示例#20
0
    def __build_snmpv3_user(self, target):
        """
        Build a UsmUserData object, based on the 'user' field of the 'target'.  Target should be a
        JSON Object.
        """
        # default object is blank
        user = {}

        if "user" in target:
            user = target["user"]

        # get username
        name = user.get("username", "")

        # get the authentication key
        auth_key = None
        if "auth_key" in user:
            auth_key = user["auth_key"]

        # get the auth_protocol and map it to the appropriate constant
        auth_protocol = None
        if "auth_protocol" in user:
            protocol = user["auth_protocol"].lower()
            if protocol == "none":
                auth_protocol = hlapi.usmNoAuthProtocol
            elif protocol == "md5":
                auth_protocol = hlapi.usmHMACMD5AuthProtocol
            elif protocol == "sha":
                auth_protocol = hlapi.usmHMACSHAAuthProtocol
            else:
                raise Exception(
                    "Configuration Error, invalid Authentication Protocol.  Valid values are 'None', 'MD5' and 'SHA'"
                )

        # get the priv_key
        priv_key = None
        if "priv_key" in user:
            priv_key = user["priv_key"]

        # get the priv_protocol and map it to the appropriate constant
        priv_protocol = hlapi.usmNoPrivProtocol
        if "priv_protocol" in user:
            protocol = user["priv_protocol"].lower()
            if protocol == "none":
                priv_protocol = hlapi.usmNoPrivProtocol
            elif protocol == "des":
                priv_protocol = hlapi.usmDESPrivProtocol
            elif protocol == "aes128":
                priv_protocol = hlapi.usmAesCfb128PrivProtocol
            elif protocol == "aes192":
                priv_protocol = hlapi.usmAesCfb192PrivProtocol
            elif protocol == "aes256":
                priv_protocol = hlapi.usmAesCfb256PrivProtocol
            elif protocol == "3des":
                priv_protocol = hlapi.usm3DESEDEPrivProtocol
            else:
                raise Exception(
                    "Configuration Error, invalid Encryption Protocol.  Valid values are 'None', 'DES', 'AES128, 'AES192', 'AES256' and '3DES'"
                )

        # create the object
        return UsmUserData(
            name,
            authKey=auth_key,
            privKey=priv_key,
            authProtocol=auth_protocol,
            privProtocol=priv_protocol,
        )