Esempio n. 1
0
        protected ISnmpMessage Read(Arguments args, ISnmpMessage request, IPEndPoint receiver)
        {
            timeoutTimer.Interval = args.Timeout;
            timeoutTimer.Enabled  = true;

            ISnmpMessage response = null;

            if (args.Command == Command.Get)
            {
                response = ((GetRequestMessage)request).GetResponse(args.Timeout, receiver);
            }
            else
            {
                response = ((SetRequestMessage)request).GetResponse(args.Timeout, receiver);
            }

            if (!timeoutTimer.Enabled)
            {
                throw ErrorException.Create("SNMP Error: Timeout while waiting for response.", receiver.Address);
            }
            else
            {
                timeoutTimer.Enabled = false;
            }

            return(response);
        }
Esempio n. 2
0
        public async Task Handle(SetV3Command command)
        {
            Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
            ReportMessage report    = discovery.GetResponse(10000, new IPEndPoint(command.IpAddress, command.Port));

            var provider = GetPrivacyProvider(command.Password, command.PasswordType, command.Encryption, command.EncryptionType);

            SetRequestMessage request = new SetRequestMessage(
                Lextm.SharpSnmpLib.VersionCode.V3,
                Messenger.NextMessageId,
                Messenger.NextRequestId,
                new OctetString(command.UserName),
                new List <Variable>
            {
                new Variable(new ObjectIdentifier(command.OID.Id), new OctetString(command.OID.Value))
            },
                provider, report);

            ISnmpMessage reply = await request.GetResponseAsync(new IPEndPoint(command.IpAddress, command.Port));

            if (reply.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
            {
                throw ErrorException.Create("error in response", command.IpAddress, reply);
            }
        }
        internal override void Get(Variable variable)
        {
            if (string.IsNullOrEmpty(UserName))
            {
                Logger.Info("User name need to be specified for v3.");
                return;
            }

            Discovery         discovery = Messenger.NextDiscovery;
            ReportMessage     report    = discovery.GetResponse(Timeout, Agent);
            GetRequestMessage request   = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(UserName), new List <Variable> {
                variable
            }, _privacy, Messenger.MaxMessageSize, report);
            ISnmpMessage response = request.GetResponse(Timeout, Agent, _registry);

            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                          "error in response",
                          Agent.Address,
                          response);
            }

            Logger.Info(response.Pdu().Variables[0].ToString(Objects));
        }
Esempio n. 4
0
        /// <summary>
        /// Get Bulk SNMP
        /// </summary>
        /// <param name="inputoid"></param>
        /// <returns></returns>
        public static List <Variable> BulkSNMP(string inputoid, string address, int port, string community)
        {
            List <Variable> retlist = new List <Variable>();

            try
            {
                GetBulkRequestMessage message = new GetBulkRequestMessage(0,
                                                                          VersionCode.V2,
                                                                          new OctetString(community),
                                                                          0,
                                                                          10,
                                                                          new List <Variable> {
                    new Variable(new ObjectIdentifier(inputoid))
                });
                ISnmpMessage response = message.GetResponse(60000, new IPEndPoint(IPAddress.Parse(address), port));
                if (response.Pdu().ErrorStatus.ToInt32() != 0)
                {
                    throw ErrorException.Create(
                              "error in response",
                              IPAddress.Parse(address),
                              response);
                }
                retlist = response.Pdu().Variables.ToList();
            }
            catch (Exception)
            {
            }
            return(retlist);
        }
Esempio n. 5
0
        public async Task <OID> Handle(GetV3Query query)
        {
            var discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
            var report    = discovery.GetResponse(10000, new IPEndPoint(query.IpAddress, query.Port));

            IPrivacyProvider provider;

            if (query.EncryptionType == EncryptionType.DES)
            {
                provider = new Security.DESPrivacyProvider(
                    new OctetString(query.Encryption),
                    new MD5AuthenticationProvider(new OctetString(query.Password)));
            }
            else
            {
                provider = new Security.AESPrivacyProvider(
                    new OctetString(query.Encryption),
                    new MD5AuthenticationProvider(new OctetString(query.Password)));
            }

            var request = new GetRequestMessage(
                Lextm.SharpSnmpLib.VersionCode.V3,
                Messenger.NextMessageId,
                Messenger.NextRequestId,
                new OctetString(query.UserName),
                new List <Variable> {
                new Variable(new ObjectIdentifier(query.OID_Id))
            },
                provider,
                Messenger.MaxMessageSize,
                report);

            var reply = await request.GetResponseAsync(new IPEndPoint(query.IpAddress, query.Port));

            var oid = reply
                      .Pdu().Variables
                      .FirstOrDefault(variable => variable.Id.ToString() == query.OID_Id);

            if (oid == null)
            {
                throw new KeyNotFoundException($"Cannot find variable with ID {query.OID_Id}");
            }

            if (reply.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
            {
                throw ErrorException.Create("error in response", query.IpAddress, reply);
            }

            return(new OID {
                Id = oid.Id.ToString(), Value = oid.Data.ToString()
            });
        }
Esempio n. 6
0
        protected void ProcessResponse(Arguments args, ISnmpMessage request, IPEndPoint receiver)
        {
            ISnmpMessage response = Read(args, request, receiver);

            if (response == null)
            {
                throw ErrorException.Create("SNMP Error: No response", receiver.Address);
            }
            else if (response.Pdu.ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create("SNMP Error: Invalid response", receiver.Address, response);
            }
            else if ((args.Command == Command.Get) && (response.Pdu.Variables.Count > 0))
            {
                OnDataReceived(response.Pdu.Variables[0].Data.ToString());
            }
        }
Esempio n. 7
0
        private ISnmpMessage DoQuery(string OID)
        {
            Discovery         discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
            ReportMessage     report    = discovery.GetResponse(5000, new IPEndPoint(IPAddress.Parse(ConnectionOptions.SNMPHost), 161));
            GetRequestMessage request   = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(ConnectionOptions.SNMPUser), new List <Variable> {
                new Variable(new ObjectIdentifier(OID))
            }, ConnectionOptions.PrivacyProvider, Messenger.MaxMessageSize, report);
            ISnmpMessage reply = request.GetResponse(5000, new IPEndPoint(IPAddress.Parse(ConnectionOptions.SNMPHost), Convert.ToInt32(ConnectionOptions.SNMPPort)));

            if (reply.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
            {
                throw ErrorException.Create(
                          "error in response",
                          IPAddress.Parse(ConnectionOptions.SNMPHost),
                          reply);
            }
            return(reply);
        }
        internal override string GetValue(Variable variable)
        {
            Discovery         discovery = Messenger.NextDiscovery;
            ReportMessage     report    = discovery.GetResponse(Timeout, Agent);
            GetRequestMessage request   = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(UserName), new List <Variable> {
                variable
            }, _privacy, Messenger.MaxMessageSize, report);
            ISnmpMessage response = request.GetResponse(Timeout, Agent, _registry);

            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                          "error in response",
                          Agent.Address,
                          response);
            }

            return(response.Pdu().Variables[0].Data.ToString());
        }
Esempio n. 9
0
        void Set(string id, int value)
        {
            SetRequestMessage request = new SetRequestMessage(Messenger.NextRequestId,
                                                              VersionCode.V2,
                                                              new OctetString("public"),
                                                              new List <Variable> {
                new Variable(new ObjectIdentifier(id), new OctetString(value.ToString()))
            });

            ISnmpMessage reply = request.GetResponse(60000, new IPEndPoint(IPAddress.Parse(LOCALHOST), 161));

            if (reply.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
            {
                throw ErrorException.Create(
                          "error in response",
                          IPAddress.Parse(LOCALHOST),
                          reply);
            }
        }
Esempio n. 10
0
        internal override void GetNext(Variable variable)
        {
            GetNextRequestMessage message = new GetNextRequestMessage(
                Messenger.NextRequestId,
                VersionCode,
                GetCommunity,
                new List <Variable> {
                variable
            });
            ISnmpMessage response = message.GetResponse(Timeout, Agent);

            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                          "error in response",
                          Agent.Address,
                          response);
            }

            Logger.Info(response.Pdu().Variables[0].ToString(Objects));
        }
        //-----------------------------------------------------------------------------
        //SNMPGETNEXT
        public void SnmpGetNext(string oidKey)
        {
            GetNextRequestMessage message = new GetNextRequestMessage(0,
                                                                      VersionCode.V2,
                                                                      community,
                                                                      new List <Variable> {
                new Variable(new ObjectIdentifier(oidKey))
            });
            ISnmpMessage response = message.GetResponse(6000, server);

            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                          "Error in response!",
                          server.Address,
                          response);
            }

            var result = response.Pdu().Variables;

            variableList = result.ToList();
        }
Esempio n. 12
0
        public static IList <Variable> GetNext(string IpAddress, string readPermissionString, string Identifier, int readPort)
        {
            GetNextRequestMessage message = new GetNextRequestMessage(0,
                                                                      VersionCode.V1,
                                                                      new OctetString(readPermissionString),
                                                                      new List <Variable> {
                new Variable(new ObjectIdentifier(Identifier))
            });
            ISnmpMessage response = message.GetResponse(60000, new IPEndPoint(IPAddress.Parse(IpAddress), readPort));

            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                          "error in response",
                          IPAddress.Parse("192.168.1.2"),
                          response);
            }

            var result = response.Pdu().Variables;

            return(result);
        }
        public void SnmpGetNext(string community, string ipAddress, string oidKey)
        {
            GetNextRequestMessage message = new GetNextRequestMessage(0,
                                                                      VersionCode.V2,
                                                                      new OctetString(community),
                                                                      new List <Variable> {
                new Variable(new ObjectIdentifier(oidKey))
            });
            ISnmpMessage response = message.GetResponse(6000, new IPEndPoint(IPAddress.Parse(ipAddress), 161));

            if (response.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw ErrorException.Create(
                          "Error in response!",
                          IPAddress.Parse(ipAddress),
                          response);
            }

            var result = response.Pdu().Variables;

            variableList = result.ToList();
        }
Esempio n. 14
0
        private void ProcessOldVersion(Arguments args, IPEndPoint receiver, List <Variable> variables)
        {
            if (args.Version != VersionCode.V3)
            {
                timeoutTimer.Interval = args.Timeout;
                timeoutTimer.Enabled  = true;

                IList <Variable> response = null;
                if (args.Command == Command.Get)
                {
                    response = Messenger.Get(args.Version, receiver, new OctetString(args.Community), variables, args.Timeout);
                }
                else
                {
                    response = Messenger.Set(args.Version, receiver, new OctetString(args.Community), variables, args.Timeout);
                }

                if (!timeoutTimer.Enabled)
                {
                    throw ErrorException.Create("SNMP Error: Timeout while waiting for response.", receiver.Address);
                }
                else
                {
                    timeoutTimer.Enabled = false;
                }

                // TODO: What are failure responses?
                if ((response == null) || (response.Count == 0))
                {
                    throw ErrorException.Create("SNMP Error: No response", receiver.Address);
                }
                else
                {
                    OnDataReceived(response[0].Data.ToString());
                }
            }
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            string      community      = "public";
            bool        showHelp       = false;
            bool        showVersion    = false;
            VersionCode version        = VersionCode.V1;
            int         timeout        = 1000;
            int         retry          = 0;
            Levels      level          = Levels.Reportable;
            string      user           = string.Empty;
            string      authentication = string.Empty;
            string      authPhrase     = string.Empty;
            string      privacy        = string.Empty;
            string      privPhrase     = string.Empty;
            bool        dump           = false;

            OptionSet p = new OptionSet()
                          .Add("c:", "Community name, (default is public)", delegate(string v) { if (v != null)
                                                                                                 {
                                                                                                     community = v;
                                                                                                 }
                               })
                          .Add("l:", "Security level, (default is noAuthNoPriv)", delegate(string v)
            {
                if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                {
                    level = Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                {
                    level = Levels.Authentication | Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHPRIV")
                {
                    level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                }
                else
                {
                    throw new ArgumentException("no such security mode: " + v);
                }
            })
                          .Add("a:", "Authentication method (MD5 or SHA)", delegate(string v) { authentication = v; })
                          .Add("A:", "Authentication passphrase", delegate(string v) { authPhrase = v; })
                          .Add("x:", "Privacy method", delegate(string v) { privacy = v; })
                          .Add("X:", "Privacy passphrase", delegate(string v) { privPhrase = v; })
                          .Add("u:", "Security name", delegate(string v) { user = v; })
                          .Add("h|?|help", "Print this help information.", delegate(string v) { showHelp = v != null; })
                          .Add("V", "Display version number of this application.", delegate(string v) { showVersion = v != null; })
                          .Add("d", "Display message dump", delegate(string v) { dump = true; })
                          .Add("t:", "Timeout value (unit is second).", delegate(string v) { timeout = int.Parse(v) * 1000; })
                          .Add("r:", "Retry count (default is 0)", delegate(string v) { retry = int.Parse(v); })
                          .Add("v:", "SNMP version (1, 2, and 3 are currently supported)", delegate(string v)
            {
                switch (int.Parse(v))
                {
                case 1:
                    version = VersionCode.V1;
                    break;

                case 2:
                    version = VersionCode.V2;
                    break;

                case 3:
                    version = VersionCode.V3;
                    break;

                default:
                    throw new ArgumentException("no such version: " + v);
                }
            });

            if (args.Length == 0)
            {
                ShowHelp(p);
                return;
            }

            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            if (showHelp)
            {
                ShowHelp(p);
                return;
            }

            if ((extra.Count - 1) % 3 != 0)
            {
                Console.WriteLine("invalid variable number: " + extra.Count);
                return;
            }

            if (showVersion)
            {
                Console.WriteLine(Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyVersionAttribute>().Version);
                return;
            }

            IPAddress ip;
            bool      parsed = IPAddress.TryParse(extra[0], out ip);

            if (!parsed)
            {
                var addresses = Dns.GetHostAddressesAsync(extra[0]);
                addresses.Wait();
                foreach (IPAddress address in
                         addresses.Result.Where(address => address.AddressFamily == AddressFamily.InterNetwork))
                {
                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            try
            {
                List <Variable> vList = new List <Variable>();
                for (int i = 1; i < extra.Count; i = i + 3)
                {
                    string type = extra[i + 1];
                    if (type.Length != 1)
                    {
                        Console.WriteLine("invalid type string: " + type);
                        return;
                    }

                    ISnmpData data;

                    switch (type[0])
                    {
                    case 'i':
                        data = new Integer32(int.Parse(extra[i + 2]));
                        break;

                    case 'u':
                        data = new Gauge32(uint.Parse(extra[i + 2]));
                        break;

                    case 't':
                        data = new TimeTicks(uint.Parse(extra[i + 2]));
                        break;

                    case 'a':
                        data = new IP(IPAddress.Parse(extra[i + 2]).GetAddressBytes());
                        break;

                    case 'o':
                        data = new ObjectIdentifier(extra[i + 2]);
                        break;

                    case 'x':
                        data = new OctetString(ByteTool.Convert(extra[i + 2]));
                        break;

                    case 's':
                        data = new OctetString(extra[i + 2]);
                        break;

                    case 'd':
                        data = new OctetString(ByteTool.ConvertDecimal(extra[i + 2]));
                        break;

                    case 'n':
                        data = new Null();
                        break;

                    default:
                        Console.WriteLine("unknown type string: " + type[0]);
                        return;
                    }

                    Variable test = new Variable(new ObjectIdentifier(extra[i]), data);
                    vList.Add(test);
                }

                IPEndPoint receiver = new IPEndPoint(ip, 161);
                if (version != VersionCode.V3)
                {
                    foreach (Variable variable in
                             Messenger.Set(version, receiver, new OctetString(community), vList, timeout))
                    {
                        Console.WriteLine(variable);
                    }

                    return;
                }

                if (string.IsNullOrEmpty(user))
                {
                    Console.WriteLine("User name need to be specified for v3.");
                    return;
                }

                IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                                                   ? GetAuthenticationProviderByName(authentication, authPhrase)
                                                   : DefaultAuthenticationProvider.Instance;

                IPrivacyProvider priv;
                if ((level & Levels.Privacy) == Levels.Privacy)
                {
#if NET452
                    priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
#else
                    Console.WriteLine("DES (ECB) is not supported by .NET Core.");
                    return;
#endif
                }
                else
                {
                    priv = new DefaultPrivacyProvider(auth);
                }

                Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.SetRequestPdu);
                ReportMessage report    = discovery.GetResponse(timeout, receiver);

                SetRequestMessage request = new SetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), vList, priv, Messenger.MaxMessageSize, report);
                ISnmpMessage      reply   = request.GetResponse(timeout, receiver);
                if (dump)
                {
                    Console.WriteLine("Request message bytes:");
                    Console.WriteLine(ByteTool.Convert(request.ToBytes()));
                    Console.WriteLine("Response message bytes:");
                    Console.WriteLine(ByteTool.Convert(reply.ToBytes()));
                }

                if (reply is ReportMessage)
                {
                    if (reply.Pdu().Variables.Count == 0)
                    {
                        Console.WriteLine("wrong report message received");
                        return;
                    }

                    var id = reply.Pdu().Variables[0].Id;
                    if (id != Messenger.NotInTimeWindow)
                    {
                        var error = id.GetErrorMessage();
                        Console.WriteLine(error);
                        return;
                    }

                    // according to RFC 3414, send a second request to sync time.
                    request = new SetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), vList, priv, Messenger.MaxMessageSize, reply);
                    reply   = request.GetResponse(timeout, receiver);
                }
                else if (reply.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                {
                    throw ErrorException.Create(
                              "error in response",
                              receiver.Address,
                              reply);
                }

                foreach (Variable v in reply.Pdu().Variables)
                {
                    Console.WriteLine(v);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
Esempio n. 16
0
        public static void Main(string[] args)
        {
            string      community      = "public";
            bool        showHelp       = false;
            bool        showVersion    = false;
            VersionCode version        = VersionCode.V2; // GET BULK is available in SNMP v2 and above.
            int         timeout        = 1000;
            int         retry          = 0;
            Levels      level          = Levels.Reportable;
            string      user           = string.Empty;
            string      authentication = string.Empty;
            string      authPhrase     = string.Empty;
            string      privacy        = string.Empty;
            string      privPhrase     = string.Empty;
            int         maxRepetitions = 10;
            int         nonRepeaters   = 0;
            bool        dump           = false;

            OptionSet p = new OptionSet()
                          .Add("c:", "Community name, (default is public)", delegate(string v) { if (v != null)
                                                                                                 {
                                                                                                     community = v;
                                                                                                 }
                               })
                          .Add("l:", "Security level, (default is noAuthNoPriv)", delegate(string v)
            {
                if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                {
                    level = Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                {
                    level = Levels.Authentication | Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHPRIV")
                {
                    level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                }
                else
                {
                    throw new ArgumentException("no such security mode: " + v);
                }
            })
                          .Add("Cn:", "Non-repeaters (default is 0)", delegate(string v) { nonRepeaters = int.Parse(v); })
                          .Add("Cr:", "Max-repetitions (default is 10)", delegate(string v) { maxRepetitions = int.Parse(v); })
                          .Add("a:", "Authentication method (MD5 or SHA)", delegate(string v) { authentication = v; })
                          .Add("A:", "Authentication passphrase", delegate(string v) { authPhrase = v; })
                          .Add("x:", "Privacy method", delegate(string v) { privacy = v; })
                          .Add("X:", "Privacy passphrase", delegate(string v) { privPhrase = v; })
                          .Add("u:", "Security name", delegate(string v) { user = v; })
                          .Add("h|?|help", "Print this help information.", delegate(string v) { showHelp = v != null; })
                          .Add("V", "Display version number of this application.", delegate(string v) { showVersion = v != null; })
                          .Add("d", "Display message dump", delegate(string v) { dump = true; })
                          .Add("t:", "Timeout value (unit is second).", delegate(string v) { timeout = int.Parse(v) * 1000; })
                          .Add("r:", "Retry count (default is 0)", delegate(string v) { retry = int.Parse(v); })
                          .Add("v:", "SNMP version (2 and 3 are currently supported)", delegate(string v)
            {
                switch (int.Parse(v))
                {
                case 2:
                    version = VersionCode.V2;
                    break;

                case 3:
                    version = VersionCode.V3;
                    break;

                default:
                    throw new ArgumentException("no such version: " + v);
                }
            });

            if (args.Length == 0)
            {
                ShowHelp(p);
                return;
            }

            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            if (showHelp)
            {
                ShowHelp(p);
                return;
            }

            if (extra.Count < 2)
            {
                Console.WriteLine("invalid variable number: " + extra.Count);
                return;
            }

            if (showVersion)
            {
                Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                return;
            }

            IPAddress ip;
            bool      parsed = IPAddress.TryParse(extra[0], out ip);

            if (!parsed)
            {
                foreach (IPAddress address in
                         Dns.GetHostAddresses(extra[0]).Where(address => address.AddressFamily == AddressFamily.InterNetwork))
                {
                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            try
            {
                List <Variable> vList = new List <Variable>();
                for (int i = 1; i < extra.Count; i++)
                {
                    Variable test = new Variable(new ObjectIdentifier(extra[i]));
                    vList.Add(test);
                }

                IPEndPoint receiver = new IPEndPoint(ip, 161);
                if (version != VersionCode.V3)
                {
                    GetBulkRequestMessage message = new GetBulkRequestMessage(0,
                                                                              version,
                                                                              new OctetString(community),
                                                                              nonRepeaters,
                                                                              maxRepetitions,
                                                                              vList);
                    ISnmpMessage response = message.GetResponse(timeout, receiver);
                    if (response.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                    {
                        throw ErrorException.Create(
                                  "error in response",
                                  receiver.Address,
                                  response);
                    }

                    foreach (Variable variable in response.Pdu().Variables)
                    {
                        Console.WriteLine(variable);
                    }

                    return;
                }

                if (string.IsNullOrEmpty(user))
                {
                    Console.WriteLine("User name need to be specified for v3.");
                    return;
                }

                IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                                                   ? GetAuthenticationProviderByName(authentication, authPhrase)
                                                   : DefaultAuthenticationProvider.Instance;

                IPrivacyProvider priv;
                if ((level & Levels.Privacy) == Levels.Privacy)
                {
                    priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                }
                else
                {
                    priv = new DefaultPrivacyProvider(auth);
                }

                Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.GetBulkRequestPdu);
                ReportMessage report    = discovery.GetResponse(timeout, receiver);

                GetBulkRequestMessage request = new GetBulkRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), nonRepeaters, maxRepetitions, vList, priv, Messenger.MaxMessageSize, report);
                ISnmpMessage          reply   = request.GetResponse(timeout, receiver);
                if (dump)
                {
                    Console.WriteLine("Request message bytes:");
                    Console.WriteLine(ByteTool.Convert(request.ToBytes()));
                    Console.WriteLine("Response message bytes:");
                    Console.WriteLine(ByteTool.Convert(reply.ToBytes()));
                }

                if (reply is ReportMessage)
                {
                    if (reply.Pdu().Variables.Count == 0)
                    {
                        Console.WriteLine("wrong report message received");
                        return;
                    }

                    var id = reply.Pdu().Variables[0].Id;
                    if (id != Messenger.NotInTimeWindow)
                    {
                        var error = id.GetErrorMessage();
                        Console.WriteLine(error);
                        return;
                    }

                    // according to RFC 3414, send a second request to sync time.
                    request = new GetBulkRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), nonRepeaters, maxRepetitions, vList, priv, Messenger.MaxMessageSize, reply);
                    reply   = request.GetResponse(timeout, receiver);
                }
                else if (reply.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                {
                    throw ErrorException.Create(
                              "error in response",
                              receiver.Address,
                              reply);
                }

                foreach (Variable v in reply.Pdu().Variables)
                {
                    Console.WriteLine(v);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
Esempio n. 17
0
        private void GetSnmpData(string _host)
        {
            //snmpwalk -v3 -l authNoPriv -u [user] -a MD5 - A [password] [host]

            IPAddress hostIP;

            if (!IPAddress.TryParse(_host, out hostIP))
            {
                try
                {
                    hostIP = Dns.GetHostAddresses(_host)[0];
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }

            try
            {
                Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
                ReportMessage report    = discovery.GetResponse(5000, new IPEndPoint(hostIP, 161));

                var auth = new MD5AuthenticationProvider(new OctetString(txtPassword.Text));
                var priv = new DefaultPrivacyProvider(auth);

                List <Variable> vList = new List <Variable>();
                foreach (OidData oidData in OidList)
                {
                    vList.Add(new Variable(new ObjectIdentifier(oidData.Oid)));
                }

                GetRequestMessage request = new GetRequestMessage(
                    VersionCode.V3,
                    Messenger.NextMessageId,
                    Messenger.NextRequestId,
                    new OctetString("read"),
                    vList,
                    priv,
                    Messenger.MaxMessageSize,
                    report);

                ISnmpMessage reply = request.GetResponse(5000, new IPEndPoint(hostIP, 161));
                if (reply.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                {
                    throw ErrorException.Create(
                              "error in response",
                              hostIP,
                              reply);
                }


                foreach (Variable v in reply.Pdu().Variables)
                {
                    lbOutput.Items.Add(v);
                }

                lbOutput.Items.Add("-------------------------------");
                Listbox_ScrollToBottom();
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
Esempio n. 18
0
        public async Task <Variable?> GetV3TsmAsync(IPAddress ip, string oid, int retries, int port, TimeSpan timeout,
                                                    X509Certificate2 certificate, TimeSpan connectionTimeout)
        {
            if (ip == null)
            {
                throw new ArgumentNullException(nameof(ip));
            }

            if (string.IsNullOrWhiteSpace(oid))
            {
                throw new ArgumentNullException(nameof(oid));
            }

            if (!Regex.IsMatch(oid, @"^(([0-9]+)\.)+[0-9]+$"))
            {
                throw new ArgumentException(oid, nameof(oid));
            }

            if (port <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(port), port.ToString());
            }

            if (retries <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(retries), retries.ToString());
            }

            if (timeout <= TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException(nameof(timeout), timeout.ToString());
            }

            if (connectionTimeout <= TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException(nameof(connectionTimeout));
            }

            if (certificate is null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }

            var startDate   = DateTime.Now;
            var snmpType    = "GET";
            var snmpVersion = $"3 {SecurityModel.Tsm}";

            var attempt = 0;
            IEnumerable <Variable> reply = new List <Variable>();

            while (attempt < retries)
            {
                try
                {
                    var receiver       = new IPEndPoint(ip, port);
                    var clientEndPoint = ip.AddressFamily == AddressFamily.InterNetwork
                        ? new IPEndPoint(IPAddress.Any, 0) : new IPEndPoint(IPAddress.IPv6Any, 0);
                    var vList = new List <Variable>()
                    {
                        new Variable(new ObjectIdentifier(oid))
                    };

                    var chain = new X509Chain();
                    chain.Build(certificate);

                    using var client = new Client(clientEndPoint);
                    client.LoadX509Certificate(chain);
                    client.SupportedCipherSuites.Add(TCipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA);

                    var auth = TsmAuthenticationProvider.Instance;
                    IPrivacyProvider priv = new TsmPrivacyProvider(auth);

                    var          request  = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, OctetString.Empty, vList, priv, Messenger.MaxMessageSize);
                    ISnmpMessage response = await request.GetSecureResponseAsync(connectionTimeout, timeout, receiver, client).ConfigureAwait(false);

                    if (response is ReportMessage)
                    {
                        if (response.Pdu().Variables.Count == 0)
                        {
                            throw new Exception("wrong report message received");
                        }

                        var id = response.Pdu().Variables[0].Id;
                        if (id != Messenger.NotInTimeWindow)
                        {
                            var error = id.GetErrorMessage();
                            throw new Exception($"ERROR: {error}");
                        }

                        // according to RFC 3414, send a second request to sync time.
                        var request2 = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, OctetString.Empty, OctetString.Empty, vList, priv, Messenger.MaxMessageSize, response);
                        response = await request2.GetSecureResponseAsync(connectionTimeout, timeout, receiver, client).ConfigureAwait(false);
                    }
                    else if (response.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                    {
                        throw ErrorException.Create(
                                  "error in response",
                                  receiver.Address,
                                  response);
                    }

                    reply = response.Pdu().Variables;
                    break;
                }
                catch (Exception ex) when(ex is SnmpException || ex is SocketException || ex is OperationCanceledException || ex is System.TimeoutException)
                {
                    if (ex is System.TimeoutException && ex.Message == "Could Not Connect To Server")
                    {
                        _Logger.LogInformation($"{ip} - DTLS failed {attempt + 1} time(s)");
                    }

                    await _SnmpLog.LogTransactionAsync(startDate, ip.ToString(), oid, null, snmpType, snmpVersion, ex.GetType().ToString(), ex.Message).ConfigureAwait(false);

                    ++attempt;
                    if (attempt >= retries)
                    {
                        throw;
                    }
                }
            }

            var type = string.Empty;
            var data = string.Empty;

            foreach (var res in reply)
            {
                type += res.Data.TypeCode;
                data += res.Data.ToString();
            }

            await _SnmpLog.LogTransactionAsync(startDate, ip.ToString(), oid, null, snmpType, snmpVersion, type, data).ConfigureAwait(false);

            return(reply.FirstOrDefault());
        }
Esempio n. 19
0
        static void Main(string[] args)
        {
            string      community      = "public";
            bool        showHelp       = false;
            bool        showVersion    = false;
            VersionCode version        = VersionCode.V1;
            int         timeout        = 1000;
            int         retry          = 0;
            Levels      level          = Levels.Reportable;
            string      user           = string.Empty;
            string      authentication = string.Empty;
            string      authPhrase     = string.Empty;
            string      privacy        = string.Empty;
            string      privPhrase     = string.Empty;

            OptionSet p = new OptionSet()
                          .Add("c:", "-c for community name, (default is public)", delegate(string v) { if (v != null)
                                                                                                        {
                                                                                                            community = v;
                                                                                                        }
                               })
                          .Add("l:", "-l for security level, (default is noAuthNoPriv)", delegate(string v)
            {
                if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                {
                    level = Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                {
                    level = Levels.Authentication | Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHPRIV")
                {
                    level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                }
                else
                {
                    throw new ArgumentException("no such security mode: " + v);
                }
            })
                          .Add("a:", "-a for authentication method (MD5 or SHA)", delegate(string v) { authentication = v; })
                          .Add("A:", "-A for authentication passphrase", delegate(string v) { authPhrase = v; })
                          .Add("x:", "-x for privacy method", delegate(string v) { privacy = v; })
                          .Add("X:", "-X for privacy passphrase", delegate(string v) { privPhrase = v; })
                          .Add("u:", "-u for security name", delegate(string v) { user = v; })
                          .Add("h|?|help", "-h, -?, -help for help.", delegate(string v) { showHelp = v != null; })
                          .Add("V", "-V to display version number of this application.", delegate(string v) { showVersion = v != null; })
                          .Add("t:", "-t for timeout value (unit is second).", delegate(string v) { timeout = int.Parse(v) * 1000; })
                          .Add("r:", "-r for retry count (default is 0)", delegate(string v) { retry = int.Parse(v); })
                          .Add("v:", "-v for SNMP version (1, 2, and 3 are currently supported)", delegate(string v)
            {
                switch (int.Parse(v))
                {
                case 1:
                    version = VersionCode.V1;
                    break;

                case 2:
                    version = VersionCode.V2;
                    break;

                case 3:
                    version = VersionCode.V3;
                    break;

                default:
                    throw new ArgumentException("no such version: " + v);
                }
            });

            List <string> extra = p.Parse(args);

            if (showHelp)
            {
                ShowHelp();
                return;
            }

            if (showVersion)
            {
                Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                return;
            }

            if (extra.Count < 2)
            {
                ShowHelp();
                return;
            }

            IPAddress ip;
            bool      parsed = IPAddress.TryParse(extra[0], out ip);

            if (!parsed)
            {
                foreach (IPAddress address in
                         Dns.GetHostAddresses(extra[0]).Where(address => address.AddressFamily == AddressFamily.InterNetwork))
                {
                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            if ((extra.Count - 1) % 3 != 0)
            {
                Console.WriteLine("invalid variable number: " + (extra.Count - 1));
                return;
            }

            try
            {
                List <Variable> vList = new List <Variable>();
                for (int i = 1; i < extra.Count; i = i + 3)
                {
                    string type = extra[i + 1];
                    if (type.Length != 1)
                    {
                        Console.WriteLine("invalid type string: " + type);
                        return;
                    }

                    ISnmpData data;

                    switch (type[0])
                    {
                    case 'i':
                        data = new Integer32(int.Parse(extra[i + 2]));
                        break;

                    case 'u':
                        data = new Gauge32(uint.Parse(extra[i + 2]));
                        break;

                    case 't':
                        data = new TimeTicks(uint.Parse(extra[i + 2]));
                        break;

                    case 'a':
                        data = new IP(IPAddress.Parse(extra[i + 2]));
                        break;

                    case 'o':
                        data = new ObjectIdentifier(extra[i + 2]);
                        break;

                    case 'x':
                        data = new OctetString(ByteTool.Convert(extra[i + 2]));
                        break;

                    case 's':
                        data = new OctetString(extra[i + 2]);
                        break;

                    case 'd':
                        data = new OctetString(ByteTool.ConvertDecimal(extra[i + 2]));
                        break;

                    case 'n':
                        data = new Null();
                        break;

                    default:
                        Console.WriteLine("unknown type string: " + type[0]);
                        return;
                    }

                    Variable test = new Variable(new ObjectIdentifier(extra[i]), data);
                    vList.Add(test);
                }

                IPEndPoint receiver = new IPEndPoint(ip, 161);
                if (version != VersionCode.V3)
                {
                    foreach (Variable variable in
                             Messenger.Set(version, receiver, new OctetString(community), vList, timeout))
                    {
                        Console.WriteLine(variable);
                    }

                    return;
                }

                if (string.IsNullOrEmpty(user))
                {
                    Console.WriteLine("User name need to be specified for v3.");
                    return;
                }

                IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                                                   ? GetAuthenticationProviderByName(authentication, authPhrase)
                                                   : DefaultAuthenticationProvider.Instance;

                IPrivacyProvider priv;
                if ((level & Levels.Privacy) == Levels.Privacy)
                {
                    priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                }
                else
                {
                    priv = new DefaultPrivacyProvider(auth);
                }

                Discovery     discovery = Messenger.NextDiscovery;
                ReportMessage report    = discovery.GetResponse(timeout, receiver);

                SetRequestMessage request = new SetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(user), vList, priv, Messenger.MaxMessageSize, report);

                ISnmpMessage response = request.GetResponse(timeout, receiver);
                if (response.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                {
                    throw ErrorException.Create(
                              "error in response",
                              receiver.Address,
                              response);
                }

                foreach (Variable v in response.Pdu().Variables)
                {
                    Console.WriteLine(v);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
Esempio n. 20
0
        public async Task <Variable?> GetV3UsmAsync(IPAddress ip, string oid, string community, int retries, int port, TimeSpan timeout,
                                                    string authPass, string privPass)
        {
            if (ip == null)
            {
                throw new ArgumentNullException(nameof(ip));
            }

            if (string.IsNullOrWhiteSpace(oid))
            {
                throw new ArgumentNullException(nameof(oid));
            }

            if (!Regex.IsMatch(oid, @"^(([0-9]+)\.)+[0-9]+$"))
            {
                throw new ArgumentException(oid, nameof(oid));
            }

            if (port <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(port), port.ToString());
            }

            if (retries <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(retries), retries.ToString());
            }

            if (timeout <= TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException(nameof(timeout), timeout.ToString());
            }

            if (string.IsNullOrWhiteSpace(authPass))
            {
                throw new ArgumentNullException(nameof(authPass));
            }

            if (string.IsNullOrWhiteSpace(privPass))
            {
                throw new ArgumentNullException(nameof(privPass));
            }

            var startDate   = DateTime.Now;
            var snmpType    = "GET";
            var snmpVersion = $"3 {SecurityModel.Usm}";

            var attempt = 0;
            IEnumerable <Variable> reply = new List <Variable>();

            while (attempt < retries)
            {
                try
                {
                    var receiver       = new IPEndPoint(ip, port);
                    var clientEndPoint = ip.AddressFamily == AddressFamily.InterNetwork
                        ? new IPEndPoint(IPAddress.Any, 0) : new IPEndPoint(IPAddress.IPv6Any, 0);
                    var vList = new List <Variable>()
                    {
                        new Variable(new ObjectIdentifier(oid))
                    };

                    using var cts = new CancellationTokenSource(timeout);
                    var discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
                    var report    = await discovery.GetResponseAsync(receiver).ConfigureAwait(false);

                    var          auth     = new SHA1AuthenticationProvider(new OctetString(authPass)); // AuthenticationPassword
                    var          priv     = new DESPrivacyProvider(new OctetString(privPass), auth);   //PrivacyPassword
                    var          request  = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(community), vList, priv, Messenger.MaxMessageSize, report);
                    ISnmpMessage response = await request.GetResponseAsync(receiver, cts.Token).ConfigureAwait(false);

                    if (response is ReportMessage)
                    {
                        if (response.Pdu().Variables.Count == 0)
                        {
                            throw new Exception("wrong report message received");
                        }

                        var id = response.Pdu().Variables[0].Id;
                        if (id != Messenger.NotInTimeWindow)
                        {
                            var error = id.GetErrorMessage();
                            throw new Exception($"ERROR: {error}");
                        }
                    }
                    else if (response.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
                    {
                        throw ErrorException.Create(
                                  "error in response",
                                  receiver.Address,
                                  response);
                    }

                    reply = response.Pdu().Variables;
                    break;
                }
                catch (Exception ex) when(ex is SnmpException || ex is SocketException || ex is OperationCanceledException || ex is System.TimeoutException)
                {
                    if (ex is System.TimeoutException && ex.Message == "Could Not Connect To Server")
                    {
                        _Logger.LogInformation($"{ip} - DTLS failed {attempt + 1} time(s)");
                    }

                    await _SnmpLog.LogTransactionAsync(startDate, ip.ToString(), oid, community, snmpType, snmpVersion, ex.GetType().ToString(), ex.Message).ConfigureAwait(false);

                    ++attempt;
                    if (attempt >= retries)
                    {
                        throw;
                    }
                }
            }

            var type = string.Empty;
            var data = string.Empty;

            foreach (var res in reply)
            {
                type += res.Data.TypeCode;
                data += res.Data.ToString();
            }

            await _SnmpLog.LogTransactionAsync(startDate, ip.ToString(), oid, community, snmpType, snmpVersion, type, data).ConfigureAwait(false);

            return(reply.FirstOrDefault());
        }