Beispiel #1
0
        public void TestResponseVersion3()
        {
            var engine = CreateEngine();

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

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

            try
            {
                IAuthenticationProvider auth = new MD5AuthenticationProvider(new OctetString("authentication"));
                IPrivacyProvider        priv = new DefaultPrivacyProvider(auth);

                var           ending    = new AutoResetEvent(false);
                var           timeout   = 3000;
                Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
                ReportMessage report    = discovery.GetResponse(timeout, serverEndPoint);

                var expected = Messenger.NextRequestId;
                GetRequestMessage request = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, expected, new OctetString("authen"), OctetString.Empty, new List <Variable> {
                    new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0"))
                }, priv, Messenger.MaxMessageSize, report);

                var source = Observable.Defer(() =>
                {
                    ISnmpMessage reply = request.GetResponse(timeout, serverEndPoint);
                    return(Observable.Return(reply));
                })
                             .RetryWithBackoffStrategy(
                    retryCount: 4,
                    retryOnError: e => e is Messaging.TimeoutException
                    );

                source.Subscribe(reply =>
                {
                    ISnmpPdu snmpPdu = reply.Pdu();
                    Assert.Equal(SnmpType.ResponsePdu, snmpPdu.TypeCode);
                    Assert.Equal(expected, reply.RequestId());
                    Assert.Equal(ErrorCode.NoError, snmpPdu.ErrorStatus.ToErrorCode());
                    ending.Set();
                });
                Assert.True(ending.WaitOne(MaxTimeout));
            }
            finally
            {
                if (SnmpMessageExtension.IsRunningOnWindows)
                {
                    engine.Stop();
                }
            }
        }
Beispiel #2
0
        public void TestConstructorV3AuthMd5()
        {
            const string bytes = "30 73" +
                                 "02 01  03 " +
                                 "30 0F " +
                                 "02  02 35 41 " +
                                 "02  03 00 FF E3" +
                                 "04 01 05" +
                                 "02  01 03" +
                                 "04 2E  " +
                                 "30 2C" +
                                 "04 0D  80 00 1F 88 80 E9 63 00  00 D6 1F F4  49 " +
                                 "02 01 0D  " +
                                 "02 01 57 " +
                                 "04 05 6C 65 78  6C 69 " +
                                 "04 0C  1C 6D 67 BF  B2 38 ED 63 DF 0A 05 24  " +
                                 "04 00 " +
                                 "30 2D  " +
                                 "04 0D 80 00  1F 88 80 E9 63 00 00 D6  1F F4 49 " +
                                 "04  00 " +
                                 "A0 1A 02  02 01 AF 02 01 00 02 01  00 30 0E 30  0C 06 08 2B  06 01 02 01 01 03 00 05  00";
            IPrivacyProvider  pair    = new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("testpass")));
            GetRequestMessage request = new GetRequestMessage(
                VersionCode.V3,
                new Header(
                    new Integer32(13633),
                    new Integer32(0xFFE3),
                    new OctetString(new byte[] { 0x5 }),
                    new Integer32(3)),
                new SecurityParameters(
                    new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00  00 D6 1F F4  49")),
                    new Integer32(0x0d),
                    new Integer32(0x57),
                    new OctetString("lexli"),
                    new OctetString(ByteTool.Convert("1C 6D 67 BF  B2 38 ED 63 DF 0A 05 24")),
                    OctetString.Empty),
                new Scope(
                    new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00  00 D6 1F F4  49")),
                    OctetString.Empty,
                    new GetRequestPdu(
                        0x01AF,
                        ErrorCode.NoError,
                        0,
                        new List <Variable>(1)
            {
                new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0"), new Null())
            })),
                pair);

            Assert.AreEqual(Levels.Authentication, request.Level);
            Assert.AreEqual(ByteTool.Convert(bytes), request.ToBytes());
        }
Beispiel #3
0
        private void txtBytes_TextChanged(object sender, EventArgs e)
        {
            tvMessage.Nodes.Clear();
            var users = new UserRegistry();
            IAuthenticationProvider authen;

            if (tscbAuthentication.SelectedIndex == 0)
            {
                authen = DefaultAuthenticationProvider.Instance;
            }
            else if (tscbAuthentication.SelectedIndex == 1)
            {
                authen = new MD5AuthenticationProvider(new OctetString(tstxtAuthentication.Text));
            }
            else
            {
                authen = new SHA1AuthenticationProvider(new OctetString(tstxtAuthentication.Text));
            }

            IPrivacyProvider privacy;

            if (tscbPrivacy.SelectedIndex == 0)
            {
                privacy = new DefaultPrivacyProvider(authen);
            }
            else if (tscbPrivacy.SelectedIndex == 1)
            {
                privacy = new DESPrivacyProvider(new OctetString(tstxtPrivacy.Text), authen);
            }
            else
            {
                privacy = new AESPrivacyProvider(new OctetString(tstxtPrivacy.Text), authen);
            }

            users.Add(new User(new OctetString(tstxtUser.Text), privacy));

            try
            {
                var messages = MessageFactory.ParseMessages(ByteTool.Convert(txtBytes.Text.Replace("\"", null).Replace("+", null)), users);
                messages.Fill(tvMessage);
            }
            catch (Exception ex)
            {
                tvMessage.Nodes.Add(ex.Message);
            }
        }
        public void TestReportFailure2()
        {
            const string            data     = "30780201033010020462d4a37602020578040101020103042f302d040b800000090340f4ecf2b113020124020200a4040762696c6c696e67040c62bc133ef237922dfa8ca39a04003030040b800000090340f4ecf2b1130400a81f02049d2b5c8c0201000201003011300f060a2b060106030f01010200410105";
            var                     bytes    = ByteTool.Convert(data);
            const string            userName = "******";
            IAuthenticationProvider auth     = new MD5AuthenticationProvider(new OctetString("testing345"));
            IPrivacyProvider        priv     = new DefaultPrivacyProvider(auth);
            var                     users    = new UserRegistry();

            users.Add(new User(new OctetString(userName), priv));
            var messages = MessageFactory.ParseMessages(bytes, users);

            Assert.Equal(1, messages.Count);
            var message = messages[0];

            Assert.Equal(1, message.Variables().Count);
            Assert.Equal("not in time window", message.Variables()[0].Id.GetErrorMessage());
        }
Beispiel #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ReportMessage"/> class.
        /// </summary>
        /// <param name="version">The version code.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The security parameters.</param>
        /// <param name="scope">The scope.</param>
        /// <param name="privacy">The privacy provider.</param>
        public ReportMessage(VersionCode version, Header header, SecurityParameters parameters, Scope scope, IPrivacyProvider privacy)
        {
            if (scope == null)
            {
                throw new ArgumentNullException("scope");
            }

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

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

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

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

            Version    = version;
            Header     = header;
            Parameters = parameters;
            Scope      = scope;
            if (!(privacy is DefaultPrivacyProvider))
            {
                Privacy = new DefaultPrivacyProvider(privacy.AuthenticationProvider);
            }
            else
            {
                Privacy = privacy;
            }

            Privacy.AuthenticationProvider.ComputeHash(Version, Header, Parameters, Scope, Privacy);
            _bytes = this.PackMessage().ToBytes();
        }
        public void TestToBytes2()
        {
            var privacy = new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication")));
            var trap    = new TrapV2Message(
                VersionCode.V3,
                318463383,
                1276263065,
                new OctetString("lextm"),
                new ObjectIdentifier("1.3.6"),
                0,
                new List <Variable>(),
                privacy,
                0x10000,
                new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449")),
                0,
                0
                );

            Assert.Equal(ByteTool.Convert(File.ReadAllBytes(Path.Combine("Resources", "trapv3auth"))), ByteTool.Convert(trap.ToBytes()));
        }
Beispiel #7
0
        public void TestConstructorV3AuthSha()
        {
            const string bytes = "30 77 02 01  03 30 0F 02  02 47 21 02  03 00 FF E3" +
                                 "04 01 05 02  01 03 04 32  30 30 04 0D  80 00 1F 88" +
                                 "80 E9 63 00  00 D6 1F F4  49 02 01 15  02 02 01 5B" +
                                 "04 08 6C 65  78 74 75 64  69 6F 04 0C  7B 62 65 AE" +
                                 "D3 8F E3 7D  58 45 5C 6C  04 00 30 2D  04 0D 80 00" +
                                 "1F 88 80 E9  63 00 00 D6  1F F4 49 04  00 A0 1A 02" +
                                 "02 56 FF 02  01 00 02 01  00 30 0E 30  0C 06 08 2B" +
                                 "06 01 02 01  01 03 00 05  00";
            IPrivacyProvider  pair    = new DefaultPrivacyProvider(new SHA1AuthenticationProvider(new OctetString("password")));
            GetRequestMessage request = new GetRequestMessage(
                VersionCode.V3,
                new Header(
                    new Integer32(0x4721),
                    new Integer32(0xFFE3),
                    new OctetString(new byte[] { 0x5 }),
                    new Integer32(3)),
                new SecurityParameters(
                    new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00  00 D6 1F F4  49")),
                    new Integer32(0x15),
                    new Integer32(0x015B),
                    new OctetString("lextudio"),
                    new OctetString(ByteTool.Convert("7B 62 65 AE D3 8F E3 7D  58 45 5C 6C")),
                    OctetString.Empty),
                new Scope(
                    new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00  00 D6 1F F4  49")),
                    OctetString.Empty,
                    new GetRequestPdu(
                        0x56FF,
                        ErrorCode.NoError,
                        0,
                        new List <Variable>(1)
            {
                new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0"), new Null())
            })),
                pair);

            Assert.AreEqual(Levels.Authentication, request.Level);
            Assert.AreEqual(ByteTool.Convert(bytes), request.ToBytes());
        }
Beispiel #8
0
        public void TestResponseVersion3_2()
        {
            var engine = CreateEngine();

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

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

            try
            {
                IAuthenticationProvider auth = new MD5AuthenticationProvider(new OctetString("authenticationauthentication"));
                IPrivacyProvider        priv = new DefaultPrivacyProvider(auth);

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

                var expected = Messenger.NextRequestId;
                GetRequestMessage request = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, expected, new OctetString("authen"), OctetString.Empty, new List <Variable> {
                    new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0"))
                }, priv, Messenger.MaxMessageSize, report);
                ISnmpMessage reply   = request.GetResponse(timeout, serverEndPoint);
                ISnmpPdu     snmpPdu = reply.Pdu();
                Assert.Equal(SnmpType.ResponsePdu, snmpPdu.TypeCode);
                Assert.Equal(expected, reply.RequestId());
                Assert.Equal(ErrorCode.NoError, snmpPdu.ErrorStatus.ToErrorCode());
            }
            finally
            {
                if (SnmpMessageExtension.IsRunningOnWindows)
                {
                    engine.Stop();
                }
            }
        }
Beispiel #9
0
        private static SnmpEngine CreateSnmpEngine(RavenServer server, ObjectStore objectStore)
        {
            (HashSet <SnmpVersion> versions, string handlerVersion) = GetVersions(server);
            var membershipProvider = CreateMembershipProvider(server, versions);

            var handlers = new[]
            {
                new HandlerMapping(handlerVersion, "GET", new GetMessageHandler()),
                new HandlerMapping(handlerVersion, "GETNEXT", new GetNextMessageHandler()),
                new HandlerMapping(handlerVersion, "GETBULK", new GetBulkMessageHandler())
            };

            var messageHandlerFactory = new MessageHandlerFactory(handlers);

            var factory = new SnmpApplicationFactory(new SnmpLogger(Logger), objectStore, membershipProvider, messageHandlerFactory);

            var listener = new Listener();

            if (versions.Contains(SnmpVersion.V3))
            {
                var authenticationPassword = server.Configuration.Monitoring.Snmp.AuthenticationPassword ?? server.Configuration.Monitoring.Snmp.Community;

                IAuthenticationProvider authenticationProvider;
                switch (server.Configuration.Monitoring.Snmp.AuthenticationProtocol)
                {
                case SnmpAuthenticationProtocol.SHA1:
                    authenticationProvider = new SHA1AuthenticationProvider(new OctetString(authenticationPassword));
                    break;

                case SnmpAuthenticationProtocol.MD5:
                    authenticationProvider = new MD5AuthenticationProvider(new OctetString(authenticationPassword));
                    break;

                default:
                    throw new InvalidOperationException($"Unknown authentication protocol '{server.Configuration.Monitoring.Snmp.AuthenticationProtocol}'.");
                }

                var privacyPassword = server.Configuration.Monitoring.Snmp.PrivacyPassword;

                IPrivacyProvider privacyProvider;
                switch (server.Configuration.Monitoring.Snmp.PrivacyProtocol)
                {
                case SnmpPrivacyProtocol.None:
                    privacyProvider = new DefaultPrivacyProvider(authenticationProvider);
                    break;

                case SnmpPrivacyProtocol.DES:
                    privacyProvider = new BouncyCastleDESPrivacyProvider(new OctetString(privacyPassword), authenticationProvider);
                    break;

                case SnmpPrivacyProtocol.AES:
                    privacyProvider = new BouncyCastleAESPrivacyProvider(new OctetString(privacyPassword), authenticationProvider);
                    break;

                default:
                    throw new InvalidOperationException($"Unknown privacy protocol '{server.Configuration.Monitoring.Snmp.AuthenticationProtocol}'.");
                }

                listener.Users.Add(new OctetString(server.Configuration.Monitoring.Snmp.AuthenticationUser), privacyProvider);
            }

            var engineGroup   = new EngineGroup();
            var engineIdField = engineGroup.GetType().GetField("_engineId", BindingFlags.Instance | BindingFlags.NonPublic);

            engineIdField.SetValue(engineGroup, new OctetString(Guid.NewGuid().ToString("N")));

            var engine = new SnmpEngine(factory, listener, engineGroup);

            engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, server.Configuration.Monitoring.Snmp.Port));
            engine.Listener.ExceptionRaised += (sender, e) =>
            {
                if (Logger.IsOperationsEnabled)
                {
                    Logger.Operations("SNMP error: " + e.Exception.Message, e.Exception);
                }
            };

            return(engine);
        }
        public async Task TestTrapV2HandlerWithV3MessageAndWrongEngineId()
        {
            var manualEvent = new ManualResetEventSlim();
            // TODO: this is a hack. review it later.
            var engineId = new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449"));
            var users    = new EngineUserRegistry();

            users.Add(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair);
            users.Add(new OctetString("authen"),
                      new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication")))
            {
                EngineIds = new[] { engineId }
            });
            if (DESPrivacyProvider.IsSupported)
            {
                users.Add(new OctetString("privacy"), new DESPrivacyProvider(new OctetString("privacyphrase"),
                                                                             new MD5AuthenticationProvider(new OctetString("authentication"))));
            }

            var count = 0;

            var trapv1        = new TrapV1MessageHandler();
            var trapv1Mapping = new HandlerMapping("v1", "TRAPV1", trapv1);

            var trapv2 = new TrapV2MessageHandler();

            trapv2.MessageReceived += (sender, args) => { count++; };
            var trapv2Mapping = new HandlerMapping("v2,v3", "TRAPV2", trapv2);

            var inform        = new InformRequestMessageHandler();
            var informMapping = new HandlerMapping("v2,v3", "INFORM", inform);

            var store          = new ObjectStore();
            var v1             = new Version1MembershipProvider(new OctetString("public"), new OctetString("public"));
            var v2             = new Version2MembershipProvider(new OctetString("public"), new OctetString("public"));
            var v3             = new Version3MembershipProvider();
            var membership     = new ComposedMembershipProvider(new IMembershipProvider[] { v1, v2, v3 });
            var handlerFactory = new MessageHandlerFactory(new[] { trapv1Mapping, trapv2Mapping, informMapping });

            var logger = new TestLogger();

            logger.Handler = (obj, args) => { manualEvent.Set(); };

            var pipelineFactory = new SnmpApplicationFactory(logger, store, membership, handlerFactory);
            var group           = new EngineGroup();
            var engine          = new SnmpEngine(pipelineFactory, new Listener {
                Users = users
            }, group);
            var daemonEndPoint = new IPEndPoint(IPAddress.Loopback, port.NextId);

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

            try
            {
                var privacy =
                    new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication")));
                var trap = new TrapV2Message(
                    VersionCode.V3,
                    1004947569,
                    234419641,
                    new OctetString("authen"),
                    new ObjectIdentifier("1.3.6"),
                    0,
                    new List <Variable>(),
                    privacy,
                    0x10000,
                    new OctetString(ByteTool.Convert("80001F8880E9630000D61FF450")),
                    0,
                    0);
                await trap.SendAsync(daemonEndPoint);

                manualEvent.Wait();

                Assert.Equal(0, count);
                Assert.Equal(new Counter32(1), group.UnknownEngineId.Data);
            }
            finally
            {
                if (SnmpMessageExtension.IsRunningOnWindows)
                {
                    engine.Stop();
                }
            }
        }
Beispiel #11
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);
            }
        }
Beispiel #12
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);
            }
        }
Beispiel #13
0
        public static void Main(string[] args)
        {
            string      community      = "public";
            bool        showHelp       = false;
            bool        showVersion    = false;
            VersionCode version        = VersionCode.V1;
            int         timeout        = 1000;
            int         retry          = 0;
            int         maxRepetitions = 10;
            Levels      level          = Levels.Reportable;
            string      user           = string.Empty;
            string      contextName    = string.Empty;
            string      authentication = string.Empty;
            string      authPhrase     = string.Empty;
            string      privacy        = string.Empty;
            string      privPhrase     = string.Empty;
            WalkMode    mode           = WalkMode.WithinSubtree;
            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("C:", "Context name", delegate(string v) { contextName = 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|version:", "SNMP version (1, 2, and 3 are currently supported)", delegate(string v)
            {
                if (v == "2c")
                {
                    v = "2";
                }

                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);
                }
            })
                          .Add("m|mode:", "WALK mode (subtree, all are supported)", delegate(string v)
            {
                if (v == "subtree")
                {
                    mode = WalkMode.WithinSubtree;
                }
                else if (v == "all")
                {
                    mode = WalkMode.Default;
                }
                else
                {
                    throw new ArgumentException("unknown argument: " + v);
                }
            })
                          .Add("Cr:", "Max-repetitions (default is 10)", delegate(string v) { maxRepetitions = int.Parse(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 || extra.Count > 2)
            {
                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
            {
                ObjectIdentifier test     = extra.Count == 1 ? new ObjectIdentifier("1.3.6.1.2.1") : new ObjectIdentifier(extra[1]);
                IList <Variable> result   = new List <Variable>();
                IPEndPoint       receiver = new IPEndPoint(ip, 161);
                if (version == VersionCode.V1)
                {
                    Messenger.Walk(version, receiver, new OctetString(community), test, result, timeout, mode);
                }
                else if (version == VersionCode.V2)
                {
                    Messenger.BulkWalk(version, receiver, new OctetString(community), new OctetString(string.IsNullOrWhiteSpace(contextName) ? string.Empty: contextName), test, result, timeout, maxRepetitions, mode, null, null);
                }
                else
                {
                    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 (DESPrivacyProvider.IsSupported)
                        {
                            priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                        }
                        else
                        {
                            Console.WriteLine("DES (ECB) is not supported by .NET Core.");
                            return;
                        }
                    }
                    else
                    {
                        priv = new DefaultPrivacyProvider(auth);
                    }

                    Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.GetBulkRequestPdu);
                    ReportMessage report    = discovery.GetResponse(timeout, receiver);
                    Messenger.BulkWalk(version, receiver, new OctetString(user), new OctetString(string.IsNullOrWhiteSpace(contextName) ? string.Empty : contextName), test, result, timeout, maxRepetitions, mode, priv, report);
                }

                foreach (Variable variable in result)
                {
                    Console.WriteLine(variable);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #14
0
        public static void Main(string[] args)
        {
            string      community      = "public";
            bool        dump           = true;
            bool        showHelp       = false;
            bool        showVersion    = false;
            VersionCode version        = VersionCode.V1;
            int         timeout        = 1000;
            int         retry          = 0;
            int         maxRepetitions = 10;
            Levels      level          = Levels.Reportable;
            string      user           = string.Empty;
            string      authentication = string.Empty;
            string      authPhrase     = string.Empty;
            string      privacy        = string.Empty;
            string      privPhrase     = string.Empty;
            WalkMode    mode           = WalkMode.WithinSubtree;

            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("d", "-d to display message dump", delegate(string v) { dump = true; })
                          .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|version:", "-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);
                }
            })
                          .Add("m|mode:", "-m for WALK mode (subtree, all are supported)", delegate(string v)
            {
                if (v == "subtree")
                {
                    mode = WalkMode.WithinSubtree;
                }
                else if (v == "all")
                {
                    mode = WalkMode.Default;
                }
                else
                {
                    throw new ArgumentException("unknown argument: " + v);
                }
            })
                          .Add("Cr:", "-Cr for max-repetitions (default is 10)", delegate(string v) { maxRepetitions = int.Parse(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 < 1 || 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]))
                {
                    if (address.AddressFamily != AddressFamily.InterNetwork)
                    {
                        continue;
                    }

                    ip = address;
                    break;
                }

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

            try
            {
                ObjectIdentifier test     = extra.Count == 1 ? new ObjectIdentifier("1.3.6.1.2.1") : new ObjectIdentifier(extra[1]);
                IList <Variable> result   = new List <Variable>();
                IPEndPoint       receiver = new IPEndPoint(ip, 161);
                if (version == VersionCode.V1)
                {
                    Messenger.Walk(version, receiver, new OctetString(community), test, result, timeout, mode);
                }
                else if (version == VersionCode.V2)
                {
                    Messenger.BulkWalk(version, receiver, new OctetString(community), test, result, timeout, maxRepetitions, mode, null, null);
                }
                else
                {
                    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);

                    Messenger.BulkWalk(version, receiver, new OctetString(user), test, result, timeout, maxRepetitions, mode, priv, report);
                }

                foreach (Variable variable in result)
                {
                    Console.WriteLine(variable);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #15
0
        private static SnmpEngine CreateSnmpEngine(RavenServer server, ObjectStore objectStore)
        {
            (HashSet <SnmpVersion> versions, string handlerVersion) = GetVersions(server);
            var membershipProvider = CreateMembershipProvider(server, versions);

            var handlers = new[]
            {
                new HandlerMapping(handlerVersion, "GET", new GetMessageHandler()),
                new HandlerMapping(handlerVersion, "GETNEXT", new GetNextMessageHandler()),
                new HandlerMapping(handlerVersion, "GETBULK", new GetBulkMessageHandler())
            };

            var messageHandlerFactory = new MessageHandlerFactory(handlers);

            var factory = new SnmpApplicationFactory(new SnmpLogger(Logger), objectStore, membershipProvider, messageHandlerFactory);

            var listener = new Listener();

            if (versions.Contains(SnmpVersion.V3))
            {
                var authenticationPassword = server.Configuration.Monitoring.Snmp.AuthenticationPassword ?? server.Configuration.Monitoring.Snmp.Community;

                IAuthenticationProvider authenticationProvider;
                switch (server.Configuration.Monitoring.Snmp.AuthenticationProtocol)
                {
                case SnmpAuthenticationProtocol.SHA1:
                    authenticationProvider = new SHA1AuthenticationProvider(new OctetString(authenticationPassword));
                    break;

                case SnmpAuthenticationProtocol.MD5:
                    authenticationProvider = new MD5AuthenticationProvider(new OctetString(authenticationPassword));
                    break;

                default:
                    throw new InvalidOperationException($"Unknown authentication protocol '{server.Configuration.Monitoring.Snmp.AuthenticationProtocol}'.");
                }

                var privacyPassword = server.Configuration.Monitoring.Snmp.PrivacyPassword;

                IPrivacyProvider privacyProvider;
                switch (server.Configuration.Monitoring.Snmp.PrivacyProtocol)
                {
                case SnmpPrivacyProtocol.None:
                    privacyProvider = new DefaultPrivacyProvider(authenticationProvider);
                    break;

                case SnmpPrivacyProtocol.DES:
                    privacyProvider = new BouncyCastleDESPrivacyProvider(new OctetString(privacyPassword), authenticationProvider);
                    break;

                case SnmpPrivacyProtocol.AES:
                    privacyProvider = new BouncyCastleAESPrivacyProvider(new OctetString(privacyPassword), authenticationProvider);
                    break;

                default:
                    throw new InvalidOperationException($"Unknown privacy protocol '{server.Configuration.Monitoring.Snmp.AuthenticationProtocol}'.");
                }

                listener.Users.Add(new OctetString(server.Configuration.Monitoring.Snmp.AuthenticationUser), privacyProvider);
            }

            int engineBoots;

            using (server.ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context))
                using (var tx = context.OpenWriteTransaction())
                {
                    var tree = tx.InnerTransaction.CreateTree(nameof(SnmpWatcher));
                    engineBoots = (int)tree.Increment("EngineBoots", 1);

                    tx.Commit();
                }

            var engineGroup = new EngineGroup(engineBoots, GetIsInTime(server.Configuration.Monitoring))
            {
                EngineId = new OctetString(server.ServerStore.GetServerId().ToString("N"))
            };

            var engine = new SnmpEngine(factory, listener, engineGroup);

            engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, server.Configuration.Monitoring.Snmp.Port));
            engine.Listener.ExceptionRaised += (sender, e) =>
            {
                if (Logger.IsOperationsEnabled)
                {
                    Logger.Operations("SNMP error: " + e.Exception.Message, e.Exception);
                }
            };

            return(engine);
        }
Beispiel #16
0
        public void TestConstructorV3Auth2()
        {
            const string bytes = "30 73" +
                                 "02 01  03 " +
                                 "30 0F " +
                                 "02  02 35 41 " +
                                 "02  03 00 FF E3" +
                                 "04 01 05" +
                                 "02  01 03" +
                                 "04 2E  " +
                                 "30 2C" +
                                 "04 0D  80 00 1F 88 80 E9 63 00  00 D6 1F F4  49 " +
                                 "02 01 0D  " +
                                 "02 01 57 " +
                                 "04 05 6C 65 78  6C 69 " +
                                 "04 0C  1C 6D 67 BF  B2 38 ED 63 DF 0A 05 24  " +
                                 "04 00 " +
                                 "30 2D  " +
                                 "04 0D 80 00  1F 88 80 E9 63 00 00 D6  1F F4 49 " +
                                 "04  00 " +
                                 "A0 1A 02  02 01 AF 02 01 00 02 01  00 30 0E 30  0C 06 08 2B  06 01 02 01 01 03 00 05  00";
            ReportMessage report = new ReportMessage(
                VersionCode.V3,
                new Header(
                    new Integer32(13633),
                    new Integer32(0xFFE3),
                    0),
                new SecurityParameters(
                    new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00  00 D6 1F F4  49")),
                    new Integer32(0x0d),
                    new Integer32(0x57),
                    new OctetString("lexli"),
                    new OctetString(new byte[12]),
                    OctetString.Empty),
                new Scope(
                    new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00  00 D6 1F F4  49")),
                    OctetString.Empty,
                    new ReportPdu(
                        0x01AF,
                        ErrorCode.NoError,
                        0,
                        new List <Variable>(1)
            {
                new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0"))
            })),
                DefaultPrivacyProvider.DefaultPair,
                null);

            IPrivacyProvider  privacy = new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("testpass")));
            GetRequestMessage request = new GetRequestMessage(
                VersionCode.V3,
                13633,
                0x01AF,
                new OctetString("lexli"),
                OctetString.Empty,
                new List <Variable>(1)
            {
                new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0"))
            },
                privacy,
                Messenger.MaxMessageSize,
                report,
                SecurityModel.Usm);

            Assert.Equal(Levels.Authentication | Levels.Reportable, request.Header.SecurityLevel);
            Assert.Equal(ByteTool.Convert(bytes), request.ToBytes());
        }
Beispiel #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);
            }
        }
Beispiel #18
0
        public async Task TestTrapV2HandlerWithV3Message()
        {
            var manualEvent = new ManualResetEventSlim();
            // TODO: this is a hack. review it later.
            var engineId = new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449"));
            var users    = new UserRegistry();

            users.Add(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair);
            users.Add(new OctetString("authen"), new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication")))
            {
                EngineId = engineId
            });
#if !NETSTANDARD
            users.Add(new OctetString("privacy"), new DESPrivacyProvider(new OctetString("privacyphrase"),
                                                                         new MD5AuthenticationProvider(new OctetString("authentication"))));
#endif
            var count = 0;

            var trapv1        = new TrapV1MessageHandler();
            var trapv1Mapping = new HandlerMapping("v1", "TRAPV1", trapv1);

            var trapv2 = new TrapV2MessageHandler();
            trapv2.MessageReceived += (sender, args) =>
            {
                count++;
                manualEvent.Set();
            };
            var trapv2Mapping = new HandlerMapping("v2,v3", "TRAPV2", trapv2);

            var inform        = new InformRequestMessageHandler();
            var informMapping = new HandlerMapping("v2,v3", "INFORM", inform);

            var store          = new ObjectStore();
            var v1             = new Version1MembershipProvider(new OctetString("public"), new OctetString("public"));
            var v2             = new Version2MembershipProvider(new OctetString("public"), new OctetString("public"));
            var v3             = new Version3MembershipProvider();
            var membership     = new ComposedMembershipProvider(new IMembershipProvider[] { v1, v2, v3 });
            var handlerFactory = new MessageHandlerFactory(new[] { trapv1Mapping, trapv2Mapping, informMapping });

            var pipelineFactory = new SnmpApplicationFactory(store, membership, handlerFactory);
            using (var engine = new SnmpEngine(pipelineFactory, new Listener {
                Users = users
            }, new EngineGroup()))
            {
                var daemonEndPoint = new IPEndPoint(IPAddress.Loopback, port.NextId);
                engine.Listener.AddBinding(daemonEndPoint);
                engine.Start();

                var privacy = new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication")));
                var trap    = new TrapV2Message(
                    VersionCode.V3,
                    1004947569,
                    234419641,
                    new OctetString("authen"),
                    new ObjectIdentifier("1.3.6"),
                    0,
                    new List <Variable>(),
                    privacy,
                    0x10000,
                    engineId,
                    0,
                    0);
                await trap.SendAsync(daemonEndPoint);

                manualEvent.Wait();

                Assert.Equal(1, count);

                engine.Stop();
            }
        }
Beispiel #19
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);
            }
        }