Exemple #1
0
        public static void Main(string[] args)
        {
            if (args.Length != 0)
            {
                return;
            }

            var users = new UserRegistry();

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

            if (AESPrivacyProviderBase.IsSupported)
            {
                users.Add(new OctetString("aes"), new AESPrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
                users.Add(new OctetString("aes192"), new AES192PrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
                users.Add(new OctetString("aes256"), new AES256PrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
            }

            var trapv1 = new TrapV1MessageHandler();

            trapv1.MessageReceived += WatcherTrapV1Received;
            var trapv1Mapping = new HandlerMapping("v1", "TRAPV1", trapv1);

            var trapv2 = new TrapV2MessageHandler();

            trapv2.MessageReceived += WatcherTrapV2Received;
            var trapv2Mapping = new HandlerMapping("v2,v3", "TRAPV2", trapv2);

            var inform = new InformRequestMessageHandler();

            inform.MessageReceived += WatcherInformRequestReceived;
            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()))
            {
                engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, 162));
                engine.Start();
                Console.WriteLine("#SNMP is available at https://sharpsnmp.com");
                Console.WriteLine("Press any key to stop . . . ");
                Console.Read();
                engine.Stop();
            }
        }
Exemple #2
0
        public void Execute()
        {
            if (_server.Configuration.Monitoring.Snmp.Enabled == false)
            {
                return;
            }

            _locker.Wait();

            try
            {
                _objectStore = CreateStore(_server);

                _snmpEngine = CreateSnmpEngine(_server, _objectStore);

                var activate = _server.ServerStore.LicenseManager.CanUseSnmpMonitoring(withNotification: true);
                if (activate)
                {
                    _snmpEngine.Start();
                }

                _server.ServerStore.DatabasesLandlord.OnDatabaseLoaded += AddDatabaseIfNecessary;
            }
            finally
            {
                _locker.Release();
            }

            AsyncHelpers.RunSync(AddDatabases);
        }
Exemple #3
0
        public void Execute()
        {
            if (_server.Configuration.Monitoring.Snmp.Enabled == false)
            {
                return;
            }

            _locker.Wait();

            try
            {
                _objectStore = CreateStore(_server);

                _snmpEngine = CreateSnmpEngine(_server, _objectStore);

                var activate = _server.ServerStore.LicenseManager.CanUseSnmpMonitoring(withNotification: true);
                if (activate)
                {
                    if (_snmpEngine.Active)
                    {
                        throw new InvalidOperationException("Cannot start SNMP Engine because it is already activated. Should not happen!");
                    }

                    _snmpEngine.Start();
                }

                _server.ServerStore.DatabasesLandlord.OnDatabaseLoaded += AddDatabaseIfNecessary;
            }
            finally
            {
                _locker.Release();
            }

            AsyncHelpers.RunSync(AddDatabases);
        }
Exemple #4
0
        private void StartListeners()
        {
            _engine.Listener.ClearBindings();
            int port = int.Parse(tstxtPort.Text, CultureInfo.InvariantCulture);

            if (tscbIP.Text == StrAllUnassigned)
            {
#if !__MonoCS__
                if (Socket.OSSupportsIPv4)
                {
                    _engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, port));
                }
#endif
                if (Socket.OSSupportsIPv6)
                {
                    _engine.Listener.AddBinding(new IPEndPoint(IPAddress.IPv6Any, port));
                }

                _engine.Start();
                return;
            }

            IPAddress address = IPAddress.Parse(tscbIP.Text);
            if (address.AddressFamily == AddressFamily.InterNetwork)
            {
#if !__MonoCS__
                if (!Socket.OSSupportsIPv4)
                {
                    MessageBox.Show(Listener.ErrorIPv4NotSupported);
                    return;
                }
#endif
                _engine.Listener.AddBinding(new IPEndPoint(address, port));
                _engine.Start();
                return;
            }

            if (!Socket.OSSupportsIPv6)
            {
                MessageBox.Show(Listener.ErrorIPv6NotSupported);
                return;
            }

            _engine.Listener.AddBinding(new IPEndPoint(address, port));
            _engine.Start();
        }
        private void StartListeners()
        {
            _engine.Listener.ClearBindings();
            int port = int.Parse(PortEntry.Text, CultureInfo.InvariantCulture);

            if (IpPicker.SelectedItem.ToString() == IpPicker.Items.FirstOrDefault())
            {
                if (Socket.OSSupportsIPv4)
                {
                    _engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, port));
                }

                if (Socket.OSSupportsIPv6)
                {
                    _engine.Listener.AddBinding(new IPEndPoint(IPAddress.IPv6Any, port));
                }

                _engine.Start();
                return;
            }

            IPAddress address = IPAddress.Parse(IpPicker.SelectedItem.ToString());

            if (address.AddressFamily == AddressFamily.InterNetwork)
            {
                if (!Socket.OSSupportsIPv4)
                {
                    DisplayAlert("Error IPv4 Not Supported", Listener.ErrorIPv4NotSupported, "OK");
                    return;
                }

                _engine.Listener.AddBinding(new IPEndPoint(address, port));
                _engine.Start();
                return;
            }

            if (!Socket.OSSupportsIPv6)
            {
                DisplayAlert("Error IPv6 Not Supported", Listener.ErrorIPv6NotSupported, "OK");
                return;
            }

            _engine.Listener.AddBinding(new IPEndPoint(address, port));
            _engine.Start();
        }
Exemple #6
0
        public async Task TestTrapV2HandlerWithV2Message()
        {
            var manualEvent = new ManualResetEventSlim();
            // TODO: this is a hack. review it later.
            var users = new UserRegistry();

            users.Add(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair);
            users.Add(new OctetString("authen"), new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication"))));
#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();

                await Messenger.SendTrapV2Async(1, VersionCode.V2, daemonEndPoint, new OctetString("public"), new ObjectIdentifier("1.3.6.1"), 500, new List <Variable>());

                manualEvent.Wait();

                Assert.Equal(1, count);

                engine.Stop();
            }
        }
Exemple #7
0
        public void Execute()
        {
            if (_server.Configuration.Monitoring.Snmp.Enabled == false)
            {
                return;
            }

            // validate license here

            _objectStore = CreateStore(_server);

            _snmpEngine = CreateSnmpEngine(_server, _objectStore);
            _snmpEngine.Start();

            _server.ServerStore.DatabasesLandlord.OnDatabaseLoaded += AddDatabaseIfNecessary;

            AsyncHelpers.RunSync(AddDatabases);
        }
Exemple #8
0
        public void Start()
        {
            try
            {
                _engine.Listener.ClearBindings();
                if (Socket.OSSupportsIPv4)
                {
                    _engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, 161));
                }

                if (Socket.OSSupportsIPv6)
                {
                    _engine.Listener.AddBinding(new IPEndPoint(IPAddress.IPv6Any, 161));
                }

                _engine.Start();
            }
            catch (Exception e)
            {
                ExceptionHelper.WriteFile(e.Message, "snmpstart");
            }
        }
Exemple #9
0
        public void Execute(RavenDBOptions serverOptions)
        {
            if (serverOptions.SystemDatabase.Configuration.Monitoring.Snmp.Enabled == false)
            {
                return;
            }

            if (IsLicenseValid() == false)
            {
                throw new InvalidOperationException("Your license does not allow you to use SNMP monitoring.");
            }

            systemDatabase   = serverOptions.SystemDatabase;
            databaseLandlord = serverOptions.DatabaseLandlord;

            objectStore = CreateStore(serverOptions);

            snmpEngine = CreateSnmpEngine(serverOptions, objectStore);
            snmpEngine.Start();

            databaseLandlord.OnDatabaseLoaded += AddDatabaseIfNecessary;
            AddDatabases();
        }
Exemple #10
0
        public static void Main(string[] args)
        {
            if (args.Length != 0)
            {
                return;
            }

            var users = new EngineUserRegistry();

            users.Add(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair);
            users.Add(
                new OctetString("authen"),
                new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication"))));
            if (DESPrivacyProvider.IsSupported)
            {
                users.Add(
                    new OctetString("privacy"),
                    new DESPrivacyProvider(
                        new OctetString("privacyphrase"),
                        new MD5AuthenticationProvider(new OctetString("authentication"))));

                // for snmpsendtrap testing
                users.Add(new OctetString("trap"),
                          new DESPrivacyProvider(
                              new OctetString("privacyphrase"),
                              new MD5AuthenticationProvider(new OctetString("authentication")))
                {
                    EngineIds = new List <OctetString> {
                        new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449"))
                    }
                });
            }
            else
            {
                Console.WriteLine("DES privacy is not supported by .NET Core natively. Switched to BouncyCastle implementation.");
                users.Add(
                    new OctetString("privacy"),
                    new Samples.BouncyCastle.BouncyCastleDESPrivacyProvider(
                        new OctetString("privacyphrase"),
                        new MD5AuthenticationProvider(new OctetString("authentication"))));

                // for snmpsendtrap testing
                users.Add(new OctetString("trap"),
                          new Samples.BouncyCastle.BouncyCastleDESPrivacyProvider(
                              new OctetString("privacyphrase"),
                              new MD5AuthenticationProvider(new OctetString("authentication")))
                {
                    EngineIds = new List <OctetString> {
                        new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449"))
                    }
                });
            }

            if (AESPrivacyProviderBase.IsSupported)
            {
                users.Add(new OctetString("aes"), new AESPrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
                users.Add(new OctetString("aes192"), new AES192PrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
                users.Add(new OctetString("aes256"), new AES256PrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));

                // for snmpsendtrap testing
                users.Add(new OctetString("trapAES"),
                          new AESPrivacyProvider(
                              new OctetString("privacyphrase"),
                              new MD5AuthenticationProvider(new OctetString("authentication")))
                {
                    EngineIds = new List <OctetString> {
                        new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449"))
                    }
                });
            }
            else
            {
                Console.WriteLine("AES privacy is not supported by .NET Core natively. Switched to BouncyCastle implementation.");
                users.Add(new OctetString("aes"), new Samples.BouncyCastle.BouncyCastleAESPrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
                users.Add(new OctetString("aes192"), new Samples.BouncyCastle.BouncyCastleAES192PrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
                users.Add(new OctetString("aes256"), new Samples.BouncyCastle.BouncyCastleAES256PrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));

                // for snmpsendtrap testing
                users.Add(new OctetString("trapAES"),
                          new Samples.BouncyCastle.BouncyCastleAESPrivacyProvider(
                              new OctetString("privacyphrase"),
                              new MD5AuthenticationProvider(new OctetString("authentication")))
                {
                    EngineIds = new List <OctetString> {
                        new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449"))
                    }
                });
            }

            var trapv1 = new TrapV1MessageHandler();

            trapv1.MessageReceived += WatcherTrapV1Received;
            var trapv1Mapping = new HandlerMapping("v1", "TRAPV1", trapv1);

            var trapv2 = new TrapV2MessageHandler();

            trapv2.MessageReceived += WatcherTrapV2Received;
            var trapv2Mapping = new HandlerMapping("v2,v3", "TRAPV2", trapv2);

            var inform = new InformRequestMessageHandler();

            inform.MessageReceived += WatcherInformRequestReceived;
            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()))
            {
                engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, 162));
                engine.Listener.ExceptionRaised += (sender, e) => Console.WriteLine($"Exception catched: {e.Exception}");
                engine.Start();
                Console.WriteLine("#SNMP is available at https://sharpsnmp.com");
                Console.WriteLine("Press any key to stop . . . ");
                Console.Read();
                engine.Stop();
            }
        }
        private async Task BackgroundProcessing(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                using (var scope = _serviceProvider.CreateScope())
                {
                    var repository = scope.ServiceProvider.GetRequiredService <ITrapUsersRepository>();

                    if (await repository.HasNewUsers(_activeTrapUsers, stoppingToken))
                    {
                        _activeTrapUsers = await repository.GetUsers();

                        var ports = _activeTrapUsers.Select(usr => usr.Port).Distinct();
                        var users = new UserRegistry();
                        users.Add(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair);

                        foreach (var trapUser in _activeTrapUsers)
                        {
                            IPrivacyProvider provider;
                            if (trapUser.EncryptionType == EncryptionType.DES)
                            {
                                provider = new DESPrivacyProvider(
                                    new OctetString(trapUser.Encryption),
                                    new MD5AuthenticationProvider(new OctetString(trapUser.Password)))
                                {
                                    EngineIds = new List <OctetString> {
                                        new OctetString(ByteTool.Convert(trapUser.EngineId))
                                    }
                                };
                            }
                            else
                            {
                                provider = new AESPrivacyProvider(
                                    new OctetString(trapUser.Encryption),
                                    new MD5AuthenticationProvider(new OctetString(trapUser.Password)))
                                {
                                    EngineIds = new List <OctetString> {
                                        new OctetString(ByteTool.Convert(trapUser.EngineId))
                                    }
                                };
                            }

                            users.Add(new OctetString(trapUser.UserName), provider);
                        }

                        var trap = new TrapV2MessageHandler();
                        trap.MessageReceived += TrapMessageReceived;
                        var trapv2Mapping = new HandlerMapping("v2,v3", "TRAPV2", trap);

                        //sudo snmptrap -v3 -e 0x090807060504030201 -l authPriv -u snmpro -a MD5 -A STrP@SSWRD -x DES -X STr0ngP@SSWRD 192.168.0.110:162 ''  1.3.6.1.4.1.8072.2.3.0.1 1.3.6.1.4.1.8072.2.3.2.1 s "Example Message"
                        var inform = new InformRequestMessageHandler();
                        inform.MessageReceived += InformMessageReceived;
                        var informMapping = new HandlerMapping("v2,v3", "INFORM", inform);

                        var membership = new ComposedMembershipProvider(new IMembershipProvider[]
                        {
                            new Version1MembershipProvider(new OctetString("public"), new OctetString("public")),
                            new Version2MembershipProvider(new OctetString("public"), new OctetString("public")),
                            new Version3MembershipProvider()
                        });

                        var handlerFactory  = new MessageHandlerFactory(new[] { trapv2Mapping, informMapping });
                        var pipelineFactory = new SnmpApplicationFactory(new ObjectStore(), membership, handlerFactory);

                        if (_engine?.Active ?? false)
                        {
                            _engine.Stop();
                            _engine.Dispose();
                        }

                        _engine = new SnmpEngine(pipelineFactory, new Listener {
                            Users = users
                        }, new EngineGroup());

                        foreach (var port in ports)
                        {
                            _engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, port));
                        }

                        _engine.Start();
                    }
                }

                await Task.Delay(5000, stoppingToken);
            }
        }
Exemple #12
0
        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 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++; };
            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();
            using (var engine = new SnmpEngine(pipelineFactory, new Listener {
                Users = users
            }, group))
            {
                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,
                    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);

                engine.Stop();
            }
        }
Exemple #13
0
        public static void Main(string[] args)
        {
            if (args.Length != 0)
            {
                return;
            }

            var store = new ObjectStore();

            store.Add(new SysDescr());
            store.Add(new SysObjectId());
            store.Add(new SysUpTime());
            store.Add(new SysContact());
            store.Add(new SysName());
            store.Add(new SysLocation());
            store.Add(new SysServices());
            store.Add(new SysORLastChange());
            store.Add(new SysORTable());
            store.Add(new IfNumber());
            store.Add(new IfTable());

            var users = new UserRegistry();

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

            if (AESPrivacyProviderBase.IsSupported)
            {
                users.Add(new OctetString("aes"), new AESPrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
                users.Add(new OctetString("aes192"), new AES192PrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
                users.Add(new OctetString("aes256"), new AES256PrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
            }

            var getv1        = new GetV1MessageHandler();
            var getv1Mapping = new HandlerMapping("v1", "GET", getv1);

            var getv23        = new GetMessageHandler();
            var getv23Mapping = new HandlerMapping("v2,v3", "GET", getv23);

            var setv1        = new SetV1MessageHandler();
            var setv1Mapping = new HandlerMapping("v1", "SET", setv1);

            var setv23        = new SetMessageHandler();
            var setv23Mapping = new HandlerMapping("v2,v3", "SET", setv23);

            var getnextv1        = new GetNextV1MessageHandler();
            var getnextv1Mapping = new HandlerMapping("v1", "GETNEXT", getnextv1);

            var getnextv23        = new GetNextMessageHandler();
            var getnextv23Mapping = new HandlerMapping("v2,v3", "GETNEXT", getnextv23);

            var getbulk        = new GetBulkMessageHandler();
            var getbulkMapping = new HandlerMapping("v2,v3", "GETBULK", getbulk);

            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[]
            {
                getv1Mapping,
                getv23Mapping,
                setv1Mapping,
                setv23Mapping,
                getnextv1Mapping,
                getnextv23Mapping,
                getbulkMapping
            });

            var pipelineFactory = new SnmpApplicationFactory(store, membership, handlerFactory);

            using (var engine = new SnmpEngine(pipelineFactory, new Listener {
                Users = users
            }, new EngineGroup()))
            {
                engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, 161));
                engine.Listener.ExceptionRaised += Engine_ExceptionRaised;
                engine.Listener.MessageReceived += RequestReceived;
                engine.Start();
                Console.WriteLine("#SNMP is available at https://sharpsnmp.com");
                Console.WriteLine("Press any key to stop . . . ");
                Console.Read();
                engine.Stop();
            }
        }
        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 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++;
                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);
            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();

            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,
                    engineId,
                    0,
                    0);
                await trap.SendAsync(daemonEndPoint);

                manualEvent.Wait();

                Assert.Equal(1, count);
            }
            finally
            {
                if (SnmpMessageExtension.IsRunningOnWindows)
                {
                    engine.Stop();
                }
            }
        }
        public async Task TestInformV2HandlerWithV3MessageDES()
        {
            var manualEvent = new ManualResetEventSlim();
            // TODO: this is a hack. review it later.
            var users = new EngineUserRegistry();

            users.Add(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair);
            users.Add(new OctetString("authen"),
                      new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication"))));
            if (DESPrivacyProvider.IsSupported)
            {
                users.Add(
                    new OctetString("privacy"),
                    new DESPrivacyProvider(
                        new OctetString("privacyphrase"),
                        new MD5AuthenticationProvider(new OctetString("authentication"))));
            }
            else
            {
                users.Add(
                    new OctetString("privacy"),
                    new BouncyCastle.BouncyCastleDESPrivacyProvider(
                        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();
            var trapv2Mapping = new HandlerMapping("v2,v3", "TRAPV2", trapv2);

            var inform = new InformRequestMessageHandler();

            inform.MessageReceived += (sender, args) =>
            {
                count++;
                manualEvent.Set();
            };
            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);
            var engine          = new SnmpEngine(pipelineFactory, new Listener {
                Users = users
            }, new EngineGroup());
            var daemonEndPoint = new IPEndPoint(IPAddress.Loopback, port.NextId);

            engine.Listener.AddBinding(daemonEndPoint);
            engine.Listener.ExceptionRaised += (sender, e) => { Assert.True(false, "unhandled exception"); };
            engine.Listener.MessageReceived += (sender, e) => { Console.WriteLine(e.Message); };
            engine.Start();

            try
            {
                Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.InformRequestPdu);
                ReportMessage report    = discovery.GetResponse(2000, daemonEndPoint);
                await Messenger.SendInformAsync(1,
                                                VersionCode.V3,
                                                daemonEndPoint,
                                                new OctetString("privacy"),
                                                OctetString.Empty,
                                                new ObjectIdentifier("1.3.6.1"),
                                                500,
                                                new List <Variable>(),
                                                DESPrivacyProvider.IsSupported
                                                ?(IPrivacyProvider) new DESPrivacyProvider(
                                                    new OctetString("privacyphrase"),
                                                    new MD5AuthenticationProvider(new OctetString("authentication")))
                                                : new BouncyCastle.BouncyCastleDESPrivacyProvider(
                                                    new OctetString("privacyphrase"),
                                                    new MD5AuthenticationProvider(new OctetString("authentication"))),
                                                report);

                manualEvent.Wait();

                Assert.Equal(1, count);
            }
            finally
            {
                if (SnmpMessageExtension.IsRunningOnWindows)
                {
                    engine.Stop();
                }
            }
        }