internal override void Set(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);
            SetRequestMessage request   = new SetRequestMessage(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));
        }
        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);
            }
        }
Exemple #3
0
        public void SetV3Async(IPAddress ipAddress, string oid, SNMPV3Security security, string username, SNMPV3AuthenticationProvider authProvider, SecureString auth, SNMPV3PrivacyProvider privProvider, SecureString priv, string data)
        {
            Task.Run(() =>
            {
                try
                {
                    var ipEndpoint = new IPEndPoint(ipAddress, Port);

                    // Discovery
                    var discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
                    var report    = discovery.GetResponse(Timeout, ipEndpoint);

                    IPrivacyProvider privacy;

                    switch (security)
                    {
                    case SNMPV3Security.AuthPriv:
                        privacy = GetPrivacy(authProvider, SecureStringHelper.ConvertToString(auth), privProvider, SecureStringHelper.ConvertToString(priv));
                        break;

                    // noAuthNoPriv
                    case SNMPV3Security.AuthNoPriv:
                        privacy = GetPrivacy(authProvider, SecureStringHelper.ConvertToString(auth));
                        break;

                    default:
                        privacy = GetPrivacy();
                        break;
                    }

                    var request = new SetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(username), OctetString.Empty, new List <Variable> {
                        new Variable(new ObjectIdentifier(oid), new OctetString(data))
                    }, privacy, Messenger.MaxMessageSize, report);
                    var reply = request.GetResponse(Timeout, ipEndpoint);

                    OnComplete();
                }
                catch (Lextm.SharpSnmpLib.Messaging.TimeoutException)
                {
                    OnTimeoutReached();
                }
                catch (ErrorException)
                {
                    OnError();
                }
            });
        }
Exemple #4
0
        public void Setv3Async(IPAddress ipAddress, string oid, SNMPv3Security security, string username, SNMPv3AuthenticationProvider authProvider, string auth, SNMPv3PrivacyProvider privProvider, string priv, string data, SNMPOptions options)
        {
            Task.Run(() =>
            {
                try
                {
                    IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, options.Port);

                    // Discovery
                    Discovery discovery  = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
                    ReportMessage report = discovery.GetResponse(options.Timeout, ipEndpoint);

                    IPrivacyProvider privacy;

                    if (security == SNMPv3Security.authPriv)
                    {
                        privacy = GetPrivacy(authProvider, auth, privProvider, priv);
                    }
                    else if (security == SNMPv3Security.authNoPriv)
                    {
                        privacy = GetPrivacy(authProvider, auth);
                    }
                    else // noAuthNoPriv
                    {
                        privacy = GetPrivacy();
                    }

                    SetRequestMessage request = new SetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(username), new List <Variable> {
                        new Variable(new ObjectIdentifier(oid), new OctetString(data))
                    }, privacy, Messenger.MaxMessageSize, report);
                    ISnmpMessage reply = request.GetResponse(options.Timeout, ipEndpoint);

                    OnComplete();
                }
                catch (Lextm.SharpSnmpLib.Messaging.TimeoutException)
                {
                    OnTimeout();
                }
                catch (ErrorException)
                {
                    OnError();
                }
            });
        }
Exemple #5
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);
            }
        }
        public void TestSetWrongLength()
        {
            var engine = CreateEngine(max255chars: true);

            engine.Listener.ClearBindings();
            var serverEndPoint = new IPEndPoint(IPAddress.Loopback, Port.NextId);

            engine.Listener.AddBinding(serverEndPoint);
            engine.Start();

            try
            {
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                var string_toolong        = new Variable((new Max255CharsObject()).Variable.Id, new OctetString(new string('x', 256)));
                SetRequestMessage message = new SetRequestMessage(0x4bed, VersionCode.V2, new OctetString(communityPublic),
                                                                  new List <Variable> {
                    string_toolong
                });

                var resp = message.GetResponse(1500, serverEndPoint, socket);
                Assert.Equal(ErrorCode.WrongLength, resp.Pdu().ErrorStatus.ToErrorCode());
                Assert.Equal(1, resp.Pdu().ErrorIndex.ToInt32());

                var wrong_type = new Variable((new Max255CharsObject()).Variable.Id, new Integer32(666));
                message = new SetRequestMessage(0x4bed, VersionCode.V2, new OctetString(communityPublic),
                                                new List <Variable> {
                    wrong_type
                });

                resp = message.GetResponse(1500, serverEndPoint, socket);
                Assert.Equal(ErrorCode.WrongType, resp.Pdu().ErrorStatus.ToErrorCode());
                Assert.Equal(1, resp.Pdu().ErrorIndex.ToInt32());
            }
            finally
            {
                if (SnmpMessageExtension.IsRunningOnWindows)
                {
                    engine.Stop();
                }
            }
        }
Exemple #7
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);
            }
        }
Exemple #8
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);
            }
        }
Exemple #9
0
        /// <summary>
        /// Imposta il valore di un oggetto
        /// </summary>
        /// <param name="objectId">Id oggetto</param>
        /// <param name="value">Valore</param>
        /// <param name="result">OUT: gestione errori</param>
        /// <returns>True se correttamente impostato</returns>
        public bool SetMessageStr(string objectId, string value, out string result)
        {
            string output  = "";
            bool   success = false;

            switch (VersionCode)
            {
            case VersionCode.V3:
            {
                //Discover
                Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
                ReportMessage report;

                try
                {
                    report = discovery.GetResponse(10000, new IPEndPoint(IpRequestManager, IpRequestPORT));
                }
                catch (Exception ex)
                {
                    ErrorString = String.Format("Message: {0}\r\nSource: {1}\r\nStackTrace:{2}", ex.Message, ex.Source, ex.StackTrace);
                    result      = output;
                    return(false);
                }

                SetRequestMessage request = new SetRequestMessage(
                    VersionCode.V3,
                    Messenger.NextMessageId,
                    Messenger.NextRequestId,
                    UName,
                    new List <Variable>
                    {
                        new Variable(new ObjectIdentifier(objectId), new OctetString(value, Encoding))
                    },
                    Priv,
                    Messenger.MaxMessageSize,
                    report);

                ISnmpMessage reply = request.GetResponse(60000, new IPEndPoint(IpRequestManager, IpRequestPORT));

                if (reply.Pdu().ErrorStatus.ToInt32() != 0)         // != ErrorCode.NoError
                {
                    ErrorString += "error in response: " + reply;
                    result       = "";
                    return(false);
                }
                success = true;
                break;
            }

            default:
            {
                try
                {
                    IList <Variable> results = Messenger.Set(VersionCode,
                                                             new IPEndPoint(IpRequestManager, IpRequestPORT),
                                                             UName,
                                                             new List <Variable> {
                            new Variable(new ObjectIdentifier(objectId), new OctetString(value, Encoding))
                        },
                                                             15000);

                    output  = results.Aggregate("", (current, var) => String.Format("{0}\r\nId: {1}\r\nData: {2}", current, var.Id, var.Data));
                    success = true;
                }
                catch (Exception ex)
                {
                    ErrorString = String.Format("Message: {0}\r\nSource: {1}\r\nStackTrace:{2}", ex.Message, ex.Source, ex.StackTrace);
                    //return false;
                }
                break;
            }
            }

            result = output;
            return(success);
        }
Exemple #10
0
        public bool Set(RSU rsu, Core.Entities.User user, string OID, SnmpType type, string value)
        {
            IPEndPoint receiver = new IPEndPoint(rsu.IP, rsu.Port);
            int        timeout  = _managerSettings.Timeout;

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

            var auth = new SHA1AuthenticationProvider(new Lextm.SharpSnmpLib.OctetString(user.SNMPv3Auth));
            var priv = new DESPrivacyProvider(new Lextm.SharpSnmpLib.OctetString(user.SNMPv3Priv), auth);

            ISnmpData data;

            try
            {
                data = ConvertStringValue2SnmpData(type, value);
            }
            catch (InvalidDataType invalidDataType) { throw invalidDataType; }
            catch (FormatException formatException) { throw formatException; }

            List <Variable> variables = new List <Variable>()
            {
                new Variable(new ObjectIdentifier(OID), data)
            };

            SetRequestMessage request = new SetRequestMessage(VersionCode.V3
                                                              , Messenger.NextMessageId
                                                              , Messenger.NextRequestId
                                                              , new OctetString(user.UserName)
                                                              , new OctetString(String.Empty)
                                                              , variables
                                                              , priv
                                                              , Messenger.MaxMessageSize
                                                              , report);

            ISnmpMessage reply = request.GetResponse(timeout, receiver);

            // Need to send again (RFC 3414)
            if (reply is ReportMessage)
            {
                //throw new ReplyIsReportMessage();
                request = new SetRequestMessage(VersionCode.V3
                                                , Messenger.NextMessageId
                                                , Messenger.NextRequestId
                                                , new OctetString(user.UserName)
                                                , new OctetString(String.Empty)
                                                , variables
                                                , priv
                                                , Messenger.MaxMessageSize
                                                , reply);

                reply = request.GetResponse(timeout, receiver);
                if (reply.Pdu().ErrorStatus.ToInt32() != 0)
                {
                    throw new InvalidDataType();
                }
            }
            else if (reply.Pdu().ErrorStatus.ToInt32() != 0)
            {
                throw new InvalidDataType();
            }

            return(true);
        }
Exemple #11
0
        public async Task <ISnmpMessage?> SetV3TsmAsync <T>(IPAddress ip, string oid, int retries, int port, TimeSpan timeout,
                                                            X509Certificate2 certificate, TimeSpan connectionTimeout, T setValue)
        {
            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    = "SET";
            var snmpVersion = $"3 {SecurityModel.Tsm}";

            var          attempt  = 0;
            ISnmpMessage?response = null;

            while (attempt < retries)
            {
                var setValueByType = setValue switch
                {
                    int x => new Variable(new ObjectIdentifier(oid), new Integer32(x)),
                    string x => new Variable(new ObjectIdentifier(oid), new OctetString(x)),
                    IPAddress x => new Variable(new ObjectIdentifier(oid), new IP(x.ToString())),
                    uint x => new Variable(new ObjectIdentifier(oid), new Gauge32(x)),
                    byte[] x => new Variable(new ObjectIdentifier(oid), new OctetString(x)),
                    _ => throw new ArgumentOutOfRangeException(nameof(setValue)),
                };

                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>()
                    {
                        setValueByType
                    };

                    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 SetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, OctetString.Empty, vList, priv, Messenger.MaxMessageSize);
                    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}");
                        }

                        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);
                    }

                    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;
                    }
                }
            }

            if (response is null)
            {
                await _SnmpLog.LogTransactionAsync(startDate, ip.ToString(), oid, null, snmpType, snmpVersion, SnmpType.Null.ToString(), null).ConfigureAwait(false);

                return(response);
            }

            var type = response.Pdu().TypeCode;
            var data = response.Pdu().ErrorStatus;

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

            return(response);
        }
Exemple #12
0
        public async Task <ISnmpMessage?> SetV3UsmAsync <T>(IPAddress ip, string oid, string community, int retries, int port, TimeSpan timeout,
                                                            string authPass, string privPass, T setValue)
        {
            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 (string.IsNullOrWhiteSpace(community))
            {
                throw new ArgumentNullException(nameof(community));
            }

            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());
            }

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

            var          attempt  = 0;
            ISnmpMessage?response = null;

            while (attempt < retries)
            {
                var setValueByType = setValue switch
                {
                    int x => new Variable(new ObjectIdentifier(oid), new Integer32(x)),
                    string x => new Variable(new ObjectIdentifier(oid), new OctetString(x)),
                    IPAddress x => new Variable(new ObjectIdentifier(oid), new IP(x.ToString())),
                    uint x => new Variable(new ObjectIdentifier(oid), new Gauge32(x)),
                    byte[] x => new Variable(new ObjectIdentifier(oid), new OctetString(x)),
                    _ => throw new ArgumentOutOfRangeException(nameof(setValue)),
                };

                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>()
                    {
                        setValueByType
                    };

                    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 SetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(community), vList, priv, report);

                    using var cts = new CancellationTokenSource(timeout);
                    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}");
                        }
                    }

                    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;
                    }
                }
            }

            if (response is null)
            {
                await _SnmpLog.LogTransactionAsync(startDate, ip.ToString(), oid, community, snmpType, snmpVersion, SnmpType.Null.ToString(), null).ConfigureAwait(false);

                return(response);
            }

            var type = response.Pdu().TypeCode;
            var data = response.Pdu().ErrorStatus;

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

            return(response);
        }
Exemple #13
0
        public async Task <ISnmpMessage?> SetV2Async <T>(IPAddress ip, string oid, string community, int retries, int port, TimeSpan timeout, T setValue)
        {
            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 (string.IsNullOrWhiteSpace(community))
            {
                throw new ArgumentNullException(nameof(community));
            }

            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());
            }

            var startDate   = DateTime.Now;
            var snmpType    = "SET";
            var snmpVersion = "2c";

            var          attempt  = 0;
            ISnmpMessage?response = null;

            while (attempt < retries)
            {
                var setValueByType = setValue switch
                {
                    int x => new Variable(new ObjectIdentifier(oid), new Integer32(x)),
                    string x => new Variable(new ObjectIdentifier(oid), new OctetString(x)),
                    IPAddress x => new Variable(new ObjectIdentifier(oid), new IP(x.ToString())),
                    uint x => new Variable(new ObjectIdentifier(oid), new Gauge32(x)),
                    byte[] x => new Variable(new ObjectIdentifier(oid), new OctetString(x)),
                    _ => throw new ArgumentOutOfRangeException(nameof(setValue)),
                };

                try
                {
                    var receiver = new IPEndPoint(ip, port);
                    var request  = new SetRequestMessage(Messenger.NextMessageId, VersionCode.V2, new OctetString(community),
                                                         new List <Variable> {
                        setValueByType
                    });

                    using var cts = new CancellationTokenSource(timeout);
                    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}");
                        }
                    }

                    break;
                }
                catch (Exception ex) when(ex is SnmpException || ex is SocketException || ex is OperationCanceledException)
                {
                    await _SnmpLog.LogTransactionAsync(startDate, ip.ToString(), oid, community, snmpType, snmpVersion, ex.GetType().ToString(), ex.Message).ConfigureAwait(false);

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

            if (response is null)
            {
                await _SnmpLog.LogTransactionAsync(startDate, ip.ToString(), oid, community, snmpType, snmpVersion, SnmpType.Null.ToString(), null).ConfigureAwait(false);

                return(response);
            }

            var type = response.Pdu().TypeCode;
            var data = response.Pdu().ErrorStatus;

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

            return(response);
        }