Exemple #1
1
        public bool sprawdzPolaczenie(string host1, string commun)
        {
            /*! 
	    	 *Sprawdza, czy pod wpisanymi danymi istnieje jakiś serwer do obsługi.
             */
            string OID = "1.3.6.1.2.1.6.11.0";
            OctetString communityOS = new OctetString(commun);
            AgentParameters param = new AgentParameters(communityOS);
            param.Version = SnmpVersion.Ver1;
            IpAddress agent = new IpAddress(host1);
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

            Pdu pdu = new Pdu(PduType.Get);
            pdu.VbList.Add(OID);
            try
            {
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
            }
            catch
            {
                return false;
            }
            host = host1;
            community = commun;
            return true;
        }
Exemple #2
1
        /// <summary>
        /// Gets a list of variable binds.
        /// </summary>
        /// <param name="version">Protocol version.</param>
        /// <param name="endpoint">Endpoint.</param>
        /// <param name="community">Community name.</param>
        /// <param name="variables">Variable binds.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <returns></returns>
        public static IList<Variable> Get(VersionCode version, IPEndPoint endpoint, OctetString community, IList<Variable> variables, int timeout)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }

            if (community == null)
            {
                throw new ArgumentNullException("community");
            }

            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }

            if (version == VersionCode.V3)
            {
                throw new NotSupportedException("SNMP v3 is not supported");
            }

            var message = new GetRequestMessage(RequestCounter.NextId, version, community, variables);
            var response = message.GetResponse(timeout, endpoint);
            var pdu = response.Pdu();
            if (pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                    "error in response",
                    endpoint.Address,
                    response);
            }

            return pdu.Variables;
        }
Exemple #3
0
 public OidUnit(string path, OctetString data)
     : base(path)
 {
     _path = path;
     _data = data;
     _index = SNMPHelper.GetObjectIndex(new ObjectIdentifier(path));
 }
        public GetResponseMessage(int requestId, VersionCode version, OctetString community, ErrorCode error, int index, IList<Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (version == VersionCode.V3)
            {
                throw new ArgumentException("Please use overload constructor for v3", "version");
            }

            Version = version;
            Header = Header.Empty;
            Parameters = new SecurityParameters(null, null, null, community, null, null);
            GetResponsePdu pdu = new GetResponsePdu(
                requestId,
                error,
                index,
                variables);
            Scope = new Scope(pdu);
            Privacy = DefaultPrivacyProvider.DefaultPair;

            _bytes = SnmpMessageExtension.PackMessage(Version, Header, Parameters, Scope, Privacy).ToBytes();
        }
Exemple #5
0
        public string get(string ip, string oid)
        {
            Pdu pdu = new Pdu(PduType.Get);
            pdu.VbList.Add(oid);
            OctetString community = new OctetString("public");
            AgentParameters param = new AgentParameters(community);
            param.Version = SnmpVersion.Ver1;
            {
                IpAddress agent = new IpAddress(ip);
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);
                if (result != null)
                {
                    if (result.Pdu.ErrorStatus != 0)
                    {

                        return string.Format("Error in SNMP reply. Error {0} index {1} \r\n",
                            result.Pdu.ErrorStatus,
                            result.Pdu.ErrorIndex);
                    }
                    else
                    {
                        return result.Pdu.VbList[0].Value.ToString();
                    }
                }

                else
                {
                    return string.Format("No response received from SNMP agent. \r\n");
                }
                target.Dispose();
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="Header"/> class.
        /// </summary>
        /// <param name="messageId">The message id.</param>
        /// <param name="maxMessageSize">Size of the max message.</param>
        /// <param name="securityBits">The flags.</param>
        /// <param name="securityModel">The security model.</param>
        /// <remarks>If you want an empty header, please use <see cref="Empty"/>.</remarks>
        public Header(Integer32 messageId, Integer32 maxMessageSize, OctetString securityBits, Integer32 securityModel)
        {
            if (messageId == null)
            {
                throw new ArgumentNullException("messageId");
            }

            if (maxMessageSize == null)
            {
                throw new ArgumentNullException("maxMessageSize");
            }

            if (securityBits == null)
            {
                throw new ArgumentNullException("securityBits");
            }

            if (securityModel == null)
            {
                throw new ArgumentNullException("securityModel");
            }

            _messageId = messageId;
            _maxSize = maxMessageSize;
            _flags = securityBits;
            _securityModel = securityModel;
        }
        /// <summary>
        /// Creates a <see cref="SetRequestMessage"/> with all contents.
        /// </summary>
        /// <param name="requestId">The request id.</param>
        /// <param name="version">Protocol version</param>
        /// <param name="community">Community name</param>
        /// <param name="variables">Variables</param>
        public SetRequestMessage(int requestId, VersionCode version, OctetString community, IList<Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (version == VersionCode.V3)
            {
                throw new ArgumentException("only v1 and v2c are supported", "version");
            }
            
            Version = version;
            Header = Header.Empty;
            Parameters = new SecurityParameters(null, null, null, community, null, null);
            SetRequestPdu pdu = new SetRequestPdu(
                requestId,
                ErrorCode.NoError,
                0,
                variables);
            Scope = new Scope(pdu);
            Privacy = DefaultPrivacyProvider.DefaultPair;
 
            _bytes = SnmpMessageExtension.PackMessage(Version, Header, Parameters, Scope, Privacy).ToBytes();
        }
        /// <summary>
        /// Creates a <see cref="SetRequestMessage"/> with all contents.
        /// </summary>
        /// <param name="requestId">The request id.</param>
        /// <param name="version">Protocol version</param>
        /// <param name="community">Community name</param>
        /// <param name="variables">Variables</param>
        public SetRequestMessage(int requestId, VersionCode version, OctetString community, IList<Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (version == VersionCode.V3)
            {
                throw new ArgumentException("only v1 and v2c are supported", "version");
            }
            
            Version = version;
            Header = Header.Empty;
            Parameters = SecurityParameters.Create(community);
            var pdu = new SetRequestPdu(
                requestId,
                variables);
            Scope = new Scope(pdu);
            Privacy = DefaultPrivacyProvider.DefaultPair;
 
            _bytes = this.PackMessage(null).ToBytes();
        }
        public void TestPhysical()
        {
            var mac = new OctetString(new byte[] {80, 90, 64, 87, 11, 99});
            Assert.AreEqual("505A40570B63", mac.ToPhysicalAddress().ToString());

            var invalid = new OctetString(new byte[] {89});
            Assert.Throws<InvalidCastException>(() => invalid.ToPhysicalAddress());
        }
 /// <summary>Constructor. Initialize the class with the value from the <see cref="OctetString"/> argument.
 /// </summary>
 /// <param name="second">Class whose value is used to initialize this class.
 /// </param>
 public EthernetAddress(OctetString second)
     : this()
 {
     if (second.Length < 6)
         throw new System.ArgumentException("Buffer underflow error converting IP address");
     else if (Length > 6)
         throw new System.ArgumentException("Buffer overflow error converting IP address");
     base.Set(second);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MD5AuthenticationProvider"/> class.
 /// </summary>
 /// <param name="phrase">The phrase.</param>
 public MD5AuthenticationProvider(OctetString phrase)
 {
     if (phrase == null)
     {
         throw new ArgumentNullException("phrase");
     }
     
     _password = phrase.GetRaw();
 }
Exemple #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MalformedMessage"/> class.
        /// </summary>
        /// <param name="messageId">The message id.</param>
        /// <param name="user">The user.</param>
        public MalformedMessage(int messageId, OctetString user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            Header = new Header(messageId);
            Parameters = SecurityParameters.Create(user);
            Scope = DefaultScope;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MalformedMessage"/> class.
        /// </summary>
        /// <param name="messageId">The message id.</param>
        /// <param name="user">The user.</param>
        public MalformedMessage(int messageId, OctetString user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            MessageId = messageId;
            Parameters = new SecurityParameters(null, null, null, user, null, null);
            Pdu = MalformedPdu.Instance;
        }
        public void TestEqual()
        {
            var left = new OctetString("public");
            var right = new OctetString("public");
            Assert.AreEqual(left, right);
            Assert.IsTrue(left != OctetString.Empty);
// ReSharper disable EqualExpressionComparison
            Assert.IsTrue(left == left);
// ReSharper restore EqualExpressionComparison

        }
Exemple #15
0
        /// <summary>
        /// Performs an SNMP get request
        /// </summary>
        /// <param name="log_options">Log options</param>
        /// <param name="ip">IP of target device</param>
        /// <param name="in_community">Community name</param>
        /// <param name="oid">OID</param>
        /// <returns></returns>
        public static SnmpV1Packet Get(LOG_OPTIONS log_options, IPAddress ip, string in_community, string oid, bool get_next)
        {
            // SNMP community name
            OctetString community = new OctetString(in_community);

            // Define agent parameters class
            AgentParameters param = new AgentParameters(community);
            // Set SNMP version to 1 (or 2)
            param.Version = SnmpVersion.Ver1;

            // Construct target
            UdpTarget target = new UdpTarget(ip, 161, 2000, 1);

            // Pdu class used for all requests
            Pdu pdu;
            if (get_next)
            {
                pdu = new Pdu(PduType.GetNext);
            }
            else
            {
                pdu = new Pdu(PduType.Get);
            }
            pdu.VbList.Add(oid); //sysDescr

            // Make SNMP request
            SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

            // If result is null then agent didn't reply or we couldn't parse the reply.
            if (result != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    Logger.Write(log_options, module, "Error in SNMP reply. Error " + result.Pdu.ErrorStatus.ToString() + " index " + result.Pdu.ErrorIndex.ToString());
                }
                else
                {
                    // Reply variables are returned in the same order as they were added
                    //  to the VbList
                    Logger.Write(log_options, module, "OID: " + result.Pdu.VbList[0].Oid.ToString() + " Value: " + SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type) + " : " + result.Pdu.VbList[0].Value.ToString());
                }
            }
            else
            {
                Logger.Write(log_options, module, "No response received from SNMP agent.");
            }
            target.Close();

            return result;
        }
Exemple #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Header"/> class.
        /// </summary>
        /// <param name="data">The data.</param>
        public Header(ISnmpData data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            Sequence container = (Sequence)data;
            _messageId = (Integer32)container[0];
            _maxSize = (Integer32)container[1];
            _flags = (OctetString)container[2];
            _securityModel = (Integer32)container[3];
        }
		/// <summary>
		/// Check the SNMP devices in the Devices.ini are available or not.
		/// If some devices are unavailable, the Devices.ini should be changed to give
		/// tester all available devices.
		/// </summary>
		/// <returns>list</returns>
		public static List<String> CheckSNMPDeviceAvailable(){			
			
		    List<string> notAvailable = new List<string>();
			int timeout = 3;
			VersionCode version = VersionCode.V1;
			IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("1.1.1.1"),161);
			OctetString community = new OctetString("public");
            
            ObjectIdentifier objectId = new ObjectIdentifier("1.3.6.1.2.1.11.1.0");
            Variable var = new Variable(objectId);   
            IList<Variable> varlist = new System.Collections.Generic.List<Variable>();
            varlist.Add(var);
            Variable data;
            IList<Variable> resultdata;
            IDictionary<string, string> AllDeviceInfo = new Dictionary<string, string> ();
            IDictionary<string, string> SNMPDeviceInfo = new Dictionary<string, string> ();
            
            AllDeviceInfo = AppConfigOper.mainOp.DevConfigs;

			foreach(string key in AllDeviceInfo.Keys)
			{
				if(key.ToUpper().StartsWith("SNMP"))
				{
					SNMPDeviceInfo.Add(key, AllDeviceInfo[key]);
				}
			}
			
			foreach (KeyValuePair<string, string>device in SNMPDeviceInfo)
			{ 
				Console.WriteLine("SNMPDeviceInfo: key={0},value={1}", device.Key, device.Value);
			}
			
            foreach(string deviceIp in SNMPDeviceInfo.Values)
            {
            	try
            	{
            		endpoint.Address = IPAddress.Parse(deviceIp);
	            	resultdata = Messenger.Get(version,endpoint,community,varlist,timeout);
	            	data = resultdata[0];
	            	Console.WriteLine("The device:" + deviceIp + "is availabe");
            	}
            	catch(Exception ex)
	            {
	            	notAvailable.Add(deviceIp);
	            	Console.WriteLine("There is no device in this ip address."+ deviceIp);
	            	string log = ex.ToString();
	            	continue;
	            }	
            }
            return notAvailable;
	   }
    public void TestEncrypt2()
    {
        byte[] expected = ByteTool.Convert("04 30 4B  4F 10 3B 73  E1 E4 BD 91  32 1B CB 41" +
 "1B A1 C1 D1  1D 2D B7 84  16 CA 41 BF  B3 62 83 C4" +
 "29 C5 A4 BC  32 DA 2E C7  65 A5 3D 71  06 3C 5B 56" +
 "FB 04 A4");
        OctetString engineId = new OctetString(ByteTool.Convert("80 00 1F 88 80  E9 63 00 00  D6 1F F4 49"));
        DESPrivacyProvider priv = new DESPrivacyProvider(new OctetString("passtest"), new MD5AuthenticationProvider(new OctetString("testpass")));
        Scope scope = new Scope(engineId, OctetString.Empty, new GetRequestPdu(0x3A25, ErrorCode.NoError, 0, new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0")) }));
        SecurityParameters parameters = new SecurityParameters(engineId, new Integer32(0x14), new Integer32(0x35), new OctetString("lexmark"), new OctetString(new byte[12]), new OctetString(ByteTool.Convert("00 00 00  01 44 2C A3 B5")));
        ISnmpData data = priv.Encrypt(scope.GetData(VersionCode.V3), parameters);
        Assert.AreEqual(SnmpType.OctetString, data.TypeCode);
        Assert.AreEqual(expected, ByteTool.ToBytes(data));
    }
Exemple #19
0
        private OctetString writeCommunity; // пароль на запись данных

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Конструктор
        /// </summary>
        public KpSnmpLogic(int number)
            : base(number)
        {
            CanSendCmd = true;
            ConnRequired = false;

            config = new Config();
            fatalError = false;
            varGroups = null;
            endPoint = null;
            readCommunity = null;
            writeCommunity = null;
            snmpVersion = VersionCode.V2;
        }
        public OctetString ComputeHash(byte[] buffer, OctetString engineId)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            if (engineId == null)
            {
                throw new ArgumentNullException("engineId");
            }

            return OctetString.Empty;
        }
Exemple #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="User"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="privacy">The privacy provider.</param>
        public User(OctetString name, IPrivacyProvider privacy)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            Name = name;
            Privacy = privacy;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SecurityParameters"/> class.
 /// </summary>
 /// <param name="parameters">The <see cref="OctetString"/> that contains parameters.</param>
 public SecurityParameters(OctetString parameters)
 {
     if (parameters == null)
     {
         throw new ArgumentNullException("parameters");
     }
     
     Sequence data = (Sequence)DataFactory.CreateSnmpData(parameters.GetRaw());
     EngineId = (OctetString)data[0];
     EngineBoots = (Integer32)data[1];
     EngineTime = (Integer32)data[2];
     UserName = (OctetString)data[3];
     AuthenticationParameters = (OctetString)data[4];
     PrivacyParameters = (OctetString)data[5];
 }
Exemple #23
0
 public TrapV1Message(VersionCode version, IPAddress agent, OctetString community, ObjectIdentifier enterprise, GenericCode generic, int specific, uint time, IList<Variable> variables)
 {
     if (variables == null)
     {
         throw new ArgumentNullException("variables");
     }
     
     if (enterprise == null)
     {
         throw new ArgumentNullException("enterprise");
     }
     
     if (community == null)
     {
         throw new ArgumentNullException("community");
     }
     
     if (agent == null)
     {
         throw new ArgumentNullException("agent");
     }
     
     if (version != VersionCode.V1)
     {
         throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "TRAP v1 is not supported in this SNMP version: {0}", version), "version");
     }
     
     Version = version;
     AgentAddress = agent;
     Community = community;
     Enterprise = enterprise;
     Generic = generic;
     Specific = specific;
     TimeStamp = time;
     var pdu = new TrapV1Pdu(
         Enterprise,
         new IP(AgentAddress),
         new Integer32((int)Generic),
         new Integer32(Specific),
         new TimeTicks(TimeStamp),
         variables);
     _pdu = pdu;
     Parameters = SecurityParameters.Create(Community);
 }
        public TrapV1Message(VersionCode version, IPAddress agent, OctetString community, ObjectIdentifier enterprise, GenericCode generic, int specific, uint time, IList<Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (enterprise == null)
            {
                throw new ArgumentNullException("enterprise");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (agent == null)
            {
                throw new ArgumentNullException("agent");
            }
            
            Version = version;
            AgentAddress = agent;
            Community = community;
            Variables = variables;
            Enterprise = enterprise;
            Generic = generic;
            Specific = specific;
            TimeStamp = time;
            TrapV1Pdu pdu = new TrapV1Pdu(
                Enterprise,
                new IP(AgentAddress),
                new Integer32((int)Generic),
                new Integer32(Specific),
                new TimeTicks(TimeStamp),
                Variables);
            Parameters = new SecurityParameters(null, null, null, Community, null, null);

            _bytes = SnmpMessageExtension.PackMessage(Version, Community, pdu).ToBytes();
        }
Exemple #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DESPrivacyProvider"/> class.
 /// </summary>
 /// <param name="phrase">The phrase.</param>
 /// <param name="auth">The auth.</param>
 public DESPrivacyProvider(OctetString phrase, IAuthenticationProvider auth)
 {
     if (phrase == null)
     {
         throw new ArgumentNullException("phrase");
     }
     
     if (auth == null)
     {
         throw new ArgumentNullException("auth");
     }
     
     // IMPORTANT: in this way privacy cannot be non-default.
     if (auth == DefaultAuthenticationProvider.Instance)
     {
         throw new ArgumentException("if authentication is off, then privacy cannot be used");
     }
     
     _phrase = phrase;
     AuthenticationProvider = auth;
 }
Exemple #26
0
        public Scope(OctetString contextEngineId, OctetString contextName, ISnmpPdu pdu)
        {
            if (contextEngineId == null)
            {
                throw new ArgumentNullException("contextEngineId");
            }

            if (contextName == null)
            {
                throw new ArgumentNullException("contextName");
            }

            if (pdu == null)
            {
                throw new ArgumentNullException("pdu");
            }

            ContextEngineId = contextEngineId;
            ContextName = contextName;
            Pdu = pdu;
        }
        /// <summary>
        /// Creates a <see cref="GetBulkRequestMessage"/> with all contents.
        /// </summary>
        /// <param name="requestId">The request ID.</param>
        /// <param name="version">Protocol version.</param>
        /// <param name="community">Community name.</param>
        /// <param name="nonRepeaters">Non-repeaters.</param>
        /// <param name="maxRepetitions">Max repetitions.</param>
        /// <param name="variables">Variables.</param>
        public GetBulkRequestMessage(int requestId, VersionCode version, OctetString community, int nonRepeaters, int maxRepetitions, IList<Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (version != VersionCode.V2)
            {
                throw new ArgumentException("only v2c are supported", "version");
            }

            if (nonRepeaters > variables.Count)
            {
                throw new ArgumentException("nonRepeaters should not be greater than variable count", "nonRepeaters");
            }

            if (maxRepetitions < 1)
            {
                throw new ArgumentException("maxRepetitions should be greater than 0", "maxRepetitions");
            }

            Version = version;
            Header = Header.Empty;
            Parameters = SecurityParameters.Create(community);
            var pdu = new GetBulkRequestPdu(
                requestId,
                nonRepeaters,
                maxRepetitions,
                variables);
            Scope = new Scope(pdu);
            Privacy = DefaultPrivacyProvider.DefaultPair;

            _bytes = this.PackMessage(null).ToBytes();
        }
Exemple #28
0
        public string getHostname(string ip)
        {
            string hostname = null;
            try
            {
                OctetString comm = new OctetString(_community);
                AgentParameters param = new AgentParameters(comm);
                param.Version = SnmpVersion.Ver1;
                IpAddress agent = new IpAddress(ip);
                UdpTarget target = new UdpTarget((IPAddress)agent,161,2000,1);
                Pdu pdu = new Pdu(PduType.Get);
                pdu.VbList.Add("1.3.6.1.2.1.1.5.0");
                SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

                if (result!=null)
                {
                    if (result.Pdu.ErrorStatus!= 0)
                    {
                        hostname = null;
                    }
                    else
                    {
                        string[] cutPdu = Regex.Split(result.Pdu.VbList[0].Value.ToString(),@"\.");
                        hostname = cutPdu[0];
                    }
                }
                else
                {
                    hostname = null;
                }
            }
            catch (Exception)
            {
                hostname = null;
            }

            return hostname;
        }
        public TrapV2Message(int requestId, VersionCode version, OctetString community, ObjectIdentifier enterprise, uint time, IList<Variable> variables)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }
            
            if (enterprise == null)
            {
                throw new ArgumentNullException("enterprise");
            }
            
            if (community == null)
            {
                throw new ArgumentNullException("community");
            }
            
            if (version != VersionCode.V2)
            {
                throw new ArgumentException("only v2c are supported", "version");
            }
            
            Version = version;
            Enterprise = enterprise;
            TimeStamp = time;
            Header = Header.Empty;
            Parameters = new SecurityParameters(null, null, null, community, null, null);
            TrapV2Pdu pdu = new TrapV2Pdu(
                requestId,
                enterprise,
                time,
                variables);
            Scope = new Scope(pdu);
            Privacy = DefaultPrivacyProvider.DefaultPair;

            _bytes = SnmpMessageExtension.PackMessage(Version, Community, pdu).ToBytes();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="GetRequestMessage"/> class.
 /// </summary>
 /// <param name="version">The version.</param>
 /// <param name="messageId">The message id.</param>
 /// <param name="requestId">The request id.</param>
 /// <param name="userName">Name of the user.</param>
 /// <param name="contextName">Context name.</param>
 /// <param name="variables">The variables.</param>
 /// <param name="privacy">The privacy provider.</param>
 /// <param name="maxMessageSize">Size of the max message.</param>
 /// <param name="report">The report.</param>
 public GetRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, OctetString contextName, IList <Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report)
     : this(version, messageId, requestId, userName, contextName, variables, privacy, maxMessageSize, report, SecurityModel.Usm)
 {
 }
Exemple #31
0
        public static void Init(string ip, string trapMcastIp, int port, int trap)
        {
            SnmpLogger  logger      = new SnmpLogger();
            ObjectStore objectStore = new ObjectStore();

            OctetString getCommunity = new OctetString("public");
            OctetString setCommunity = new OctetString("public");

            IMembershipProvider[] membershipProviders = new IMembershipProvider[]
            {
                new Version1MembershipProvider(getCommunity, setCommunity),
                new Version2MembershipProvider(getCommunity, setCommunity),
                new Version3MembershipProvider()
            };
            IMembershipProvider composedMembershipProvider = new ComposedMembershipProvider(membershipProviders);

            TrapV1MessageHandler        trapv1 = new TrapV1MessageHandler();
            TrapV2MessageHandler        trapv2 = new TrapV2MessageHandler();
            InformRequestMessageHandler inform = new InformRequestMessageHandler();

            HandlerMapping[] handlerMappings = new HandlerMapping[]
            {
                new HandlerMapping("v1", "GET", new GetV1MessageHandler()),
                new HandlerMapping("v2,v3", "GET", new GetMessageHandler()),
                new HandlerMapping("v1", "SET", new SetV1MessageHandler()),
                new HandlerMapping("v2,v3", "SET", new SetMessageHandler()),
                new HandlerMapping("v1", "GETNEXT", new GetNextV1MessageHandler()),
                new HandlerMapping("v2,v3", "GETNEXT", new GetNextMessageHandler()),
                new HandlerMapping("v2,v3", "GETBULK", new GetBulkMessageHandler()),
                new HandlerMapping("v1", "TRAPV1", trapv1),
                new HandlerMapping("v2,v3", "TRAPV2", trapv2),
                new HandlerMapping("v2,v3", "INFORM", inform),
                new HandlerMapping("*", "*", new NullMessageHandler())
            };
            MessageHandlerFactory messageHandlerFactory = new MessageHandlerFactory(handlerMappings);

            User[] users = new User[]
            {
                new User(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair),
                new User(new OctetString("authen"), new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication")))),
                new User(new OctetString("privacy"), new DESPrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))))
            };
            UserRegistry userRegistry = new UserRegistry(users);

            EngineGroup engineGroup = new EngineGroup();
            Listener    listener    = new Listener()
            {
                Users = userRegistry
            };
            SnmpApplicationFactory factory = new SnmpApplicationFactory(logger, objectStore, composedMembershipProvider, messageHandlerFactory);

            _engine = new SnmpEngine(factory, listener, engineGroup);
            _engine.Listener.AddBinding(new IPEndPoint(IPAddress.Parse(ip), port));
            _engine.Listener.AddBinding(new IPEndPoint(IPAddress.Parse(ip), trap));
//			_engine.Listener.AddBinding(new IPEndPoint(IPAddress.Parse(ip), trap), trapMcastIp != null ? IPAddress.Parse(trapMcastIp) : null);
            _engine.ExceptionRaised += (sender, e) => _logger.Error("ERROR Snmp", e.Exception);

            _closed  = false;
            _store   = objectStore;
            _context = SynchronizationContext.Current ?? new SynchronizationContext();

            trapv1.MessageReceived += TrapV1Received;
            trapv2.MessageReceived += TrapV2Received;
            inform.MessageReceived += InformRequestReceived;

            (new IPEndPoint(IPAddress.Parse(ip), 0)).SetAsDefault();
        }
Exemple #32
0
 public SysORDescr(int index, OctetString description)
     : base("1.3.6.1.2.1.1.9.1.3.{0}", index)
 {
     _data = description;
 }
        /// <summary>
        /// Creates a <see cref="GetBulkRequestMessage"/> with a specific <see cref="Sequence"/>.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="messageId">The message id.</param>
        /// <param name="requestId">The request id.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="nonRepeaters">The non repeaters.</param>
        /// <param name="maxRepetitions">The max repetitions.</param>
        /// <param name="variables">The variables.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="maxMessageSize">Size of the max message.</param>
        /// <param name="report">The report.</param>
        public GetBulkRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, int nonRepeaters, int maxRepetitions, IList <Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report)
        {
            if (variables == null)
            {
                throw new ArgumentNullException("variables");
            }

            if (userName == null)
            {
                throw new ArgumentNullException("userName");
            }

            if (version != VersionCode.V3)
            {
                throw new ArgumentException("only v3 is supported", "version");
            }

            if (report == null)
            {
                throw new ArgumentNullException("report");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            if (nonRepeaters > variables.Count)
            {
                throw new ArgumentException("nonRepeaters should not be greater than variable count", "nonRepeaters");
            }

            if (maxRepetitions < 1)
            {
                throw new ArgumentException("maxRepetitions should be greater than 0", "maxRepetitions");
            }

            Version = version;
            Privacy = privacy;

            // TODO: define more constants.
            Header = new Header(new Integer32(messageId), new Integer32(maxMessageSize), privacy.ToOctetString(true));
            var parameters             = report.Parameters;
            var authenticationProvider = Privacy.AuthenticationProvider;

            Parameters = new SecurityParameters(
                parameters.EngineId,
                parameters.EngineBoots,
                parameters.EngineTime,
                userName,
                authenticationProvider.CleanDigest,
                Privacy.Salt);
            GetBulkRequestPdu pdu = new GetBulkRequestPdu(
                requestId,
                nonRepeaters,
                maxRepetitions,
                variables);
            var scope = report.Scope;

            Scope = new Scope(scope.ContextEngineId, scope.ContextName, pdu);

            authenticationProvider.ComputeHash(Version, Header, Parameters, Scope, Privacy);
            _bytes = this.PackMessage().ToBytes();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="GetRequestMessage"/> class.
 /// </summary>
 /// <param name="version">The version.</param>
 /// <param name="messageId">The message id.</param>
 /// <param name="requestId">The request id.</param>
 /// <param name="userName">Name of the user.</param>
 /// <param name="variables">The variables.</param>
 /// <param name="privacy">The privacy provider.</param>
 /// <param name="maxMessageSize">Size of the max message.</param>
 /// <param name="report">The report.</param>
 public GetRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, IList <Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report)
     : this(version, messageId, requestId, userName, OctetString.Empty, variables, privacy, maxMessageSize, report)
 {
 }
Exemple #35
0
        /// <summary>
        /// Discovers agents of the specified version in a specific time interval.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="broadcastAddress">The broadcast address.</param>
        /// <param name="community">The community.</param>
        /// <param name="interval">The discovering time interval, in milliseconds.</param>
        /// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks>
        public async Task DiscoverAsync(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int interval)
        {
            if (broadcastAddress == null)
            {
                throw new ArgumentNullException("broadcastAddress");
            }

            if (version != VersionCode.V3 && community == null)
            {
                throw new ArgumentNullException("community");
            }

            var addressFamily = broadcastAddress.AddressFamily;

            if (addressFamily == AddressFamily.InterNetworkV6)
            {
                throw new ArgumentException("IP v6 is not yet supported", "broadcastAddress");
            }

            byte[] bytes;
            _requestId = Messenger.NextRequestId;
            if (version == VersionCode.V3)
            {
                // throw new NotSupportedException("SNMP v3 is not supported");
                var discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
                bytes = discovery.ToBytes();
            }
            else
            {
                var message = new GetRequestMessage(_requestId, version, community, _defaultVariables);
                bytes = message.ToBytes();
            }

            using (var udp = new Socket(addressFamily, SocketType.Dgram, ProtocolType.Udp))
            {
                var info = SocketExtension.EventArgsFactory.Create();
                info.RemoteEndPoint = broadcastAddress;
                info.SetBuffer(bytes, 0, bytes.Length);
                using (var awaitable1 = new SocketAwaitable(info))
                {
                    await udp.SendToAsync(awaitable1);
                }

                var activeBefore = Interlocked.CompareExchange(ref _active, Active, Inactive);
                if (activeBefore == Active)
                {
                    // If already started, we've nothing to do.
                    return;
                }

                _bufferSize = udp.ReceiveBufferSize;
                await ReceiveAsync(udp).ConfigureAwait(false);

                await Task.Delay(interval).ConfigureAwait(false);

                Interlocked.CompareExchange(ref _active, Inactive, Active);
                udp.Shutdown(SocketShutdown.Both);
            }
        }
 public SetRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, IList <Variable> variables, IPrivacyProvider privacy, ISnmpMessage report)
     : this(version, messageId, requestId, userName, variables, privacy, 0xFFE3, report)
 {
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="GetRequestMessage"/> class.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="messageId">The message id.</param>
        /// <param name="requestId">The request id.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="contextName">Context name.</param>
        /// <param name="variables">The variables.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="maxMessageSize">Size of the max message.</param>
        /// <param name="report">The report.</param>
        /// <param name="securityModel">The type of security model</param>
        public GetRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, OctetString contextName, IList <Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report, SecurityModel securityModel)
        {
            if (userName == null)
            {
                throw new ArgumentNullException(nameof(userName));
            }

            if (variables == null)
            {
                throw new ArgumentNullException(nameof(variables));
            }

            if (contextName == null)
            {
                throw new ArgumentNullException(nameof(contextName));
            }

            if (version != VersionCode.V3)
            {
                throw new ArgumentException("Only v3 is supported.", nameof(version));
            }

            if (report == null)
            {
                throw new ArgumentNullException(nameof(report));
            }

            Version = version;
            Privacy = privacy ?? throw new ArgumentNullException(nameof(privacy));

            Header = new Header(new Integer32(messageId), new Integer32(maxMessageSize), privacy.ToSecurityLevel() | Levels.Reportable, new Integer32((int)securityModel));
            var parameters             = report.Parameters;
            var authenticationProvider = Privacy.AuthenticationProvider;

            if (securityModel == SecurityModel.Tsm)
            {
                Parameters = SecurityParameters.Empty;
            }
            else
            {
                Parameters = new SecurityParameters(
                    parameters.EngineId,
                    parameters.EngineBoots,
                    parameters.EngineTime,
                    userName,
                    authenticationProvider.CleanDigest,
                    Privacy.Salt);
            }

            var pdu = new GetRequestPdu(
                requestId,
                variables);
            var scope           = report.Scope;
            var contextEngineId = scope.ContextEngineId == OctetString.Empty ? parameters.EngineId : scope.ContextEngineId;

            if (contextEngineId == null)
            {
                throw new SnmpException("invalid REPORT message");
            }

            Scope = new Scope(contextEngineId, contextName, pdu);

            Privacy.ComputeHash(Version, Header, Parameters, Scope);
            _bytes = this.PackMessage(null).ToBytes();
        }
Exemple #38
0
 /// <summary>
 /// Adds the specified user name.
 /// </summary>
 /// <param name="userName">Name of the user.</param>
 /// <param name="privacy">The privacy provider.</param>
 public UserRegistry Add(OctetString userName, IPrivacyProvider privacy)
 {
     return(Add(new User(userName, privacy)));
 }
Exemple #39
0
        /// <summary>
        /// Discovers agents of the specified version in a specific time interval.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="broadcastAddress">The broadcast address.</param>
        /// <param name="community">The community.</param>
        /// <param name="interval">The discovering time interval, in milliseconds.</param>
        /// <remarks><paramref name="broadcastAddress"/> must be an IPv4 address. IPv6 is not yet supported here.</remarks>
        public void Discover(VersionCode version, IPEndPoint broadcastAddress, OctetString community, int interval)
        {
            if (broadcastAddress == null)
            {
                throw new ArgumentNullException("broadcastAddress");
            }

            if (version != VersionCode.V3 && community == null)
            {
                throw new ArgumentNullException("community");
            }

            var addressFamily = broadcastAddress.AddressFamily;

            if (addressFamily == AddressFamily.InterNetworkV6)
            {
                throw new ArgumentException("IP v6 is not yet supported", "broadcastAddress");
            }

            byte[] bytes;
            _requestId = Messenger.NextRequestId;
            if (version == VersionCode.V3)
            {
                // throw new NotSupportedException("SNMP v3 is not supported");
                var discovery = new Discovery(Messenger.NextMessageId, _requestId, Messenger.MaxMessageSize);
                bytes = discovery.ToBytes();
            }
            else
            {
                var message = new GetRequestMessage(_requestId, version, community, _defaultVariables);
                bytes = message.ToBytes();
            }

            using (var udp = new UdpClient(addressFamily))
            {
                #if (!CF)
                udp.EnableBroadcast = true;
                #endif
                udp.Send(bytes, bytes.Length, broadcastAddress);

                var activeBefore = Interlocked.CompareExchange(ref _active, Active, Inactive);
                if (activeBefore == Active)
                {
                    // If already started, we've nothing to do.
                    return;
                }

                #if CF
                _bufferSize = 8192;
                #else
                _bufferSize = udp.Client.ReceiveBufferSize;
                #endif

                #if ASYNC
                ThreadPool.QueueUserWorkItem(AsyncBeginReceive);
                #else
                ThreadPool.QueueUserWorkItem(AsyncReceive, udp.Client);
                #endif

                Thread.Sleep(interval);
                Interlocked.CompareExchange(ref _active, Inactive, Active);
                udp.Close();
            }
        }
Exemple #40
0
 public MalformedMessage(int messageId, OctetString user)
     : this(messageId, user, null)
 {
 }
 public GetBulkRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, int nonRepeaters, int maxRepetitions, IList <Variable> variables, IPrivacyProvider privacy, ISnmpMessage report)
     : this(version, messageId, requestId, userName, nonRepeaters, maxRepetitions, variables, privacy, 0xFFE3, report)
 {
 }
Exemple #42
-1
        //**********************************************************************
        /// <summary>
        /// Check the SNMP devices in the Devices.ini are available or not.
        /// If some devices are unavailable, the Devices.ini should be changed to give
        /// tester all available devices.
        /// Author: Sashimi.
        /// </summary>
        public static List<String> CheckSNMPDeviceAvailable(List<string> keyName)
        {
            List<string> notAvailable = new List<string>();
            // There are all devices in Device.ini.
            string groupName="SNMPDevices";
            //GXT_Ip_Port=10.146.88.10:163
            string keyName_IpPort = "SNMP_GXT_Ip_Port";
            string ipPort = myparseToValue(groupName,keyName_IpPort);
            string IP_Port = "";
            if(ipPort.IndexOf(":") != -1)
            {
                string[] spilt = ipPort.Split(':');
                IP_Port = spilt[0];
            }

            int timeout = 3;
            VersionCode version = VersionCode.V1;
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("1.1.1.1"),161);
            OctetString community = new OctetString("public");

            ObjectIdentifier objectId = new ObjectIdentifier("1.3.6.1.2.1.11.1.0");
            Variable var = new Variable(objectId);
            IList<Variable> varlist = new System.Collections.Generic.List<Variable>();
            varlist.Add(var);
            Variable data;
            IList<Variable> resultdata;

            foreach(string deviceIP in keyName){
                string strIP = myparseToValue(groupName,deviceIP);
                try
                {
                    if(!deviceIP.Equals("SNMP_GXT_Ip_Port"))
                        endpoint.Address = IPAddress.Parse(strIP);
                    else
                        endpoint.Address = IPAddress.Parse(IP_Port);
                     resultdata = Messenger.Get(version,endpoint,community,varlist,timeout);
                     data = resultdata[0];
                     Console.WriteLine("The device:" + deviceIP + "("+ strIP +")"+ " is availabe");
                }
                catch(Exception ex)
                {
                    notAvailable.Add(deviceIP);
                    Console.WriteLine("There is no device in this ip address."+ deviceIP + "("+ strIP +")!" );
                    string log = ex.ToString();
                    continue;
                }
            }

            return notAvailable;
        }