public void CreateTrapV2MessageReceivedEventArgs(IPEndPoint sender, TrapV2Message request, IListenerBinding binding, IList <IMembershipProvider> matchedMemberships, IList <EngineUser> matchedUsers)
 {
     Sender             = sender ?? throw new ArgumentNullException(nameof(sender));
     TrapV2Message      = request ?? throw new ArgumentNullException(nameof(request));
     Binding            = binding ?? throw new ArgumentNullException(nameof(binding));
     MatchedMemberships = matchedMemberships;
     MatchedUsers       = matchedUsers;
 }
        public void TestToBytes3()
        {
            if (!DESPrivacyProvider.IsSupported)
            {
                return;
            }

            var privacy = new DESPrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication")));
            var trap    = new TrapV2Message(
                VersionCode.V3,
                new Header(
                    new Integer32(1004947569),
                    new Integer32(0x10000),
                    privacy.ToSecurityLevel()),
                new SecurityParameters(
                    new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449")),
                    Integer32.Zero,
                    Integer32.Zero,
                    new OctetString("lextm"),
                    new OctetString(ByteTool.Convert("61A9A486AF4A861BD5C0BB1F")),
                    new OctetString(ByteTool.Convert("0000000069D39B2A"))),
                new Scope(OctetString.Empty, OctetString.Empty,
                          new TrapV2Pdu(
                              234419641,
                              new ObjectIdentifier("1.3.6"),
                              0,
                              new List <Variable>())),
                privacy,
                null);

            byte[]       bytes    = trap.ToBytes();
            UserRegistry registry = new UserRegistry();

            registry.Add(new OctetString("lextm"), privacy);
            IList <ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, registry);

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

            Assert.Equal("80001F8880E9630000D61FF449", message.Parameters.EngineId.ToHexString());
            Assert.Equal(0, message.Parameters.EngineBoots.ToInt32());
            Assert.Equal(0, message.Parameters.EngineTime.ToInt32());
            Assert.Equal("lextm", message.Parameters.UserName.ToString());
            Assert.Equal("61A9A486AF4A861BD5C0BB1F", message.Parameters.AuthenticationParameters.ToHexString());
            Assert.Equal("0000000069D39B2A", message.Parameters.PrivacyParameters.ToHexString());
            Assert.Equal("", message.Scope.ContextEngineId.ToHexString()); // SNMP#NET returns string.Empty here.
            Assert.Equal("", message.Scope.ContextName.ToHexString());
            Assert.Equal(0, message.Scope.Pdu.Variables.Count);
            Assert.Equal(1004947569, message.MessageId());
            Assert.Equal(234419641, message.RequestId());
        }
Esempio n. 3
0
 public void TestToBytes()
 {
     var trap = new TrapV2Message(
         VersionCode.V3,
         528732060,
         1905687779,
         new OctetString("lextm"),
         new ObjectIdentifier("1.3.6"),
         0,
         new List<Variable>(),
         DefaultPrivacyProvider.DefaultPair,
         0x10000,
         new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449")),
         0,
         0
        );
     Assert.AreEqual(ByteTool.Convert(Properties.Resources.trapv3), ByteTool.Convert(trap.ToBytes()));
 }
        public void TestToBytes()
        {
            var trap = new TrapV2Message(
                VersionCode.V3,
                528732060,
                1905687779,
                new OctetString("lextm"),
                new ObjectIdentifier("1.3.6"),
                0,
                new List <Variable>(),
                DefaultPrivacyProvider.DefaultPair,
                0x10000,
                new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449")),
                0,
                0
                );

            Assert.Equal(ByteTool.Convert(File.ReadAllBytes(Path.Combine("Resources", "trapv3"))), ByteTool.Convert(trap.ToBytes()));
        }
Esempio n. 5
0
 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.AreEqual(ByteTool.Convert(Properties.Resources.trapv3auth), ByteTool.Convert(trap.ToBytes()));
 }
Esempio n. 6
0
 public void TestToBytes3()
 {
     var privacy = new DESPrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication")));
     var trap = new TrapV2Message(
         VersionCode.V3,
         new Header(
             new Integer32(1004947569),
             new Integer32(0x10000),
             privacy.ToSecurityLevel()),
         new SecurityParameters(
             new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449")),
             Integer32.Zero,
             Integer32.Zero,
             new OctetString("lextm"),
             new OctetString(ByteTool.Convert("61A9A486AF4A861BD5C0BB1F")), 
             new OctetString(ByteTool.Convert("0000000069D39B2A"))),
         new Scope(OctetString.Empty, OctetString.Empty,
                   new TrapV2Pdu(
                       234419641,
                       new ObjectIdentifier("1.3.6"),
                       0,
                       new List<Variable>())),
         privacy, 
         null);         
     byte[] bytes = trap.ToBytes();
     UserRegistry registry = new UserRegistry();
     registry.Add(new OctetString("lextm"), privacy);
     IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, registry);
     Assert.AreEqual(1, messages.Count);
     ISnmpMessage message = messages[0];
     Assert.AreEqual("80001F8880E9630000D61FF449", message.Parameters.EngineId.ToHexString());
     Assert.AreEqual(0, message.Parameters.EngineBoots.ToInt32());
     Assert.AreEqual(0, message.Parameters.EngineTime.ToInt32());
     Assert.AreEqual("lextm", message.Parameters.UserName.ToString());
     Assert.AreEqual("61A9A486AF4A861BD5C0BB1F", message.Parameters.AuthenticationParameters.ToHexString());
     Assert.AreEqual("0000000069D39B2A", message.Parameters.PrivacyParameters.ToHexString());
     Assert.AreEqual("", message.Scope.ContextEngineId.ToHexString()); // SNMP#NET returns string.Empty here.
     Assert.AreEqual("", message.Scope.ContextName.ToHexString());
     Assert.AreEqual(0, message.Scope.Pdu.Variables.Count);
     Assert.AreEqual(1004947569, message.MessageId());
     Assert.AreEqual(234419641, message.RequestId());
 }
        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()));
        }
Esempio n. 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TrapV2MessageReceivedEventArgs"/> class.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="request">The request.</param>
        /// <param name="binding">The binding.</param>
        public TrapV2MessageReceivedEventArgs(IPEndPoint sender, TrapV2Message request, IListenerBinding binding)
        {
            if (sender == null)
            {
                throw new ArgumentNullException("sender");
            }

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

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

            Sender        = sender;
            TrapV2Message = request;
            Binding       = binding;
        }
Esempio n. 9
0
        protected override void Append(LoggingEvent loggingEvent)
        {
            string message = RenderLoggingEvent(loggingEvent);
            var    vars    = new List <Variable>();

            vars.Add(new Variable(new Oid(OIDprefix), new OctetString(message)));
            TrapV2Message trap;

            lock (Msglock)
            {
                trap = new TrapV2Message(
                    requestId++,
                    VersionCode.V2,
                    new OctetString(community),
                    new Oid(enterprise),
                    Convert.ToUInt32(DateTimeOffset.UtcNow.ToUnixTimeSeconds()),
                    vars);
            }

            trap.Send(new IPEndPoint(IPAddress.Parse(serverip), safeParseInt(serverport, 162)));
        }
Esempio n. 10
0
        public static void Trap(ObjectIdentifier oid, ISnmpData data, params IPEndPoint[] eps)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                try
                {
                    List <Variable> vList = new List <Variable> {
                        new Variable(oid, data)
                    };

#if !DEBUG
                    /** 20190123 Para seleccionar la IP SOURCE del TRAP */
                    using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                    {
                        var endPointLocal = new IPEndPoint(IPAddress.Parse(Properties.Settings.Default.SipIp), 0);
                        sender.Bind(endPointLocal);

                        foreach (IPEndPoint ep in eps)
                        {
                            TrapV2Message message = new TrapV2Message(0,
                                                                      VersionCode.V2,
                                                                      new OctetString("public"),
                                                                      new ObjectIdentifier(Settings.Default.BaseOid),
                                                                      0, vList);

                            message.Send(ep, sender);
                        }
                    }
#else
                    foreach (IPEndPoint ep in eps)
                    {
                        Messenger.SendTrapV2(0, VersionCode.V2, ep, new OctetString("public"), new ObjectIdentifier(Settings.Default.BaseOid), 0, vList);
                    }
#endif
                }
                catch (Exception /*e*/)
                {
                }
            });
        }
Esempio n. 11
0
        public void TrapFromTo(string ipFrom, string ipTo, string community, string oid, string val, Int32 port = 162, VersionCode snmpVersion = VersionCode.V2)
        {
            using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                var variables = new List <Variable>()
                {
                    new Variable(new ObjectIdentifier(oid), new OctetString(val))
                };
                var endPointLocal = new IPEndPoint(IPAddress.Parse(ipFrom), 0);
                var receiver      = new IPEndPoint(IPAddress.Parse(ipTo), port);

                sender.Bind(endPointLocal);

                TrapV2Message message = new TrapV2Message(0,
                                                          VersionCode.V2,
                                                          new OctetString(community),
                                                          new ObjectIdentifier(oid),
                                                          0,
                                                          variables);

                message.Send(receiver, sender);
            }
        }
Esempio n. 12
0
        public void Test()
        {
            var mock           = new Mock <ISnmpContext>();
            var mock2          = new Mock <IListenerBinding>();
            IList <Variable> v = new List <Variable>();
            var message        = new TrapV2Message(0, VersionCode.V2, new OctetString("community"), new ObjectIdentifier("1.3.6"), 0, v);

            mock.Setup(foo => foo.Binding).Returns(mock2.Object);
            mock.Setup(foo => foo.Request).Returns(message);
            mock.Setup(foo => foo.Sender).Returns(new IPEndPoint(IPAddress.Any, 0));
            mock.Setup(foo => foo.CopyRequest(ErrorCode.NoError, 0)).Verifiable("this must be called");
            var handler = new TrapV2MessageHandler();

            Assert.Throws <ArgumentNullException>(() => handler.Handle(null, null));
            Assert.Throws <ArgumentNullException>(() => handler.Handle(mock.Object, null));
            handler.MessageReceived += delegate(object args, TrapV2MessageReceivedEventArgs e)
            {
                Assert.AreEqual(mock2.Object, e.Binding);
                Assert.AreEqual(message, e.TrapV2Message);
                Assert.IsTrue(new IPEndPoint(IPAddress.Any, 0).Equals(e.Sender));
            };
            handler.Handle(mock.Object, new ObjectStore());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="TrapV2MessageReceivedEventArgs"/> class.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="request">The request.</param>
 /// <param name="binding">The binding.</param>
 /// <param name="matchedMemberships">the members</param>
 /// <param name="matchedUsers">the uers</param>
 public TrapV2MessageReceivedEventArgs(IPEndPoint sender, TrapV2Message request, IListenerBinding binding, IList <IMembershipProvider> matchedMemberships, IList <EngineUser> matchedUsers)
 {
     CreateTrapV2MessageReceivedEventArgs(sender, request, binding, matchedMemberships, matchedUsers);
 }
        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();
                }
            }
        }
Esempio n. 15
0
        //-----------------------------------------------
        private void TraiteMessagesATraiter()
        {
            if (m_nWaitingCounter > 5)
            {
                return;
            }
            m_nWaitingCounter++;
            lock (typeof(CLockerTraiteMessage))
            {
                m_nWaitingCounter--;
                List <ISnmpMessage> lstMessages = new List <ISnmpMessage>();
                lock (m_listeMessagesATraiter)
                {
                    lstMessages.AddRange(m_listeMessagesATraiter);
                    m_listeMessagesATraiter.Clear();
                }



                foreach (ISnmpMessage message in lstMessages)
                {
                    m_nNbMessages++;
                    DateTime      dtChrono   = DateTime.Now;
                    string        strIpAgent = "";
                    TrapV1Message trapV1     = message as TrapV1Message;
                    TrapV2Message trapV2     = message as TrapV2Message;
                    if (trapV1 != null)
                    {
                        m_gestionnaireAlarmes.Trace.Write(
                            "Trap received : " + trapV1.GetTraceInfo(),
                            ALTRACE.TRACE, ALTRACE.DEBUG);
                        strIpAgent = trapV1.AgentAddress.ToString();
                        StringBuilder bl = new StringBuilder();
                        foreach (Variable valeur in trapV1.Variables())
                        {
                            bl.Append(valeur.Id.ToString());
                            bl.Append("=");
                            bl.Append(valeur.Data.ToString());
                            bl.Append("\r\n");
                        }
                        m_gestionnaireAlarmes.Trace.Write(
                            "Trap fields : \r\n" + bl.ToString(),
                            ALTRACE.TRACE, ALTRACE.DEBUG);
                    }
                    else if (trapV2 != null)
                    {
                        m_gestionnaireAlarmes.Trace.Write(
                            "Trap received : " + trapV2.GetTraceInfo(),
                            ALTRACE.TRACE, ALTRACE.DEBUG);
                        if (trapV2.SenderIP != null)
                        {
                            strIpAgent = trapV2.SenderIP.ToString();
                        }
                        StringBuilder bl = new StringBuilder();
                        foreach (Variable valeur in trapV2.Variables())
                        {
                            bl.Append(valeur.Id.ToString());
                            bl.Append("=");
                            bl.Append(valeur.Data.ToString());
                            bl.Append("\r\n");
                        }
                        m_gestionnaireAlarmes.Trace.Write(
                            "Trap fields : \r\n" + bl.ToString(),
                            ALTRACE.TRACE, ALTRACE.DEBUG);
                    }
                    try
                    {
                        CTrapInstance trapTmp = CTrapInstance.FromMessage(message, null);
                        if (trapTmp == null)
                        {
                            m_gestionnaireAlarmes.Trace.Write(
                                "Can not interpret message " + message.ToString(), ALTRACE.TRACE, ALTRACE.DEBUG);
                            continue;
                        }
                        IEnumerable <CAgentSnmpPourSupervision> lstAgents = GetAgentsForTrap(trapTmp, strIpAgent);


                        bool bHasAgent = false;

                        foreach (CAgentSnmpPourSupervision agent in lstAgents)
                        {
                            m_gestionnaireAlarmes.Trace.Write(
                                "Trap managed by agent " + agent.Id,
                                ALTRACE.DEBUG);
                            CTypeAgentPourSupervision typeAgent = agent.TypeAgent;
                            if (typeAgent != null)
                            {
                                CTrapInstance trap = CTrapInstance.FromMessage(
                                    message,
                                    agent);
                                if (trap != null)
                                {
                                    IEnumerable <CTrapHandler> lstTrapsHandlers = typeAgent.GetTrapsHandlersAAppliquer(trap);
                                    foreach (CTrapHandler handler in lstTrapsHandlers)
                                    {
                                        m_gestionnaireAlarmes.Trace.Write("Apply trap handler " + handler.Libelle,
                                                                          ALTRACE.DEBUG);
                                        handler.CreateAlarmesOnTrap(trap, m_gestionnaireAlarmes.Trace);
                                    }
                                    if (lstTrapsHandlers.Count() == 0)
                                    {
                                        m_gestionnaireAlarmes.Trace.Write(
                                            "No trap handler for this trap",
                                            ALTRACE.DEBUG);
                                    }

                                    foreach (CAlarmeACreer creation in trap.AlarmesACreer)
                                    {
                                        m_gestionnaireAlarmes.CreateAlarme(creation, EModeRemonteeAlarmes.InscrireARemonterMaisNePasLeFaire);
                                    }

                                    if (trap.AlarmesACreer.Count() == 0)
                                    {
                                        m_gestionnaireAlarmes.Trace.Write("No alarm creator for this trap",
                                                                          ALTRACE.DEBUG);
                                    }
                                }
                            }
                        }
                        if (!bHasAgent)
                        {
                            m_gestionnaireAlarmes.Trace.Write(
                                "No agent for this trap",
                                ALTRACE.DEBUG);
                        }
                    }

                    catch (Exception ex)
                    {
                        m_gestionnaireAlarmes.Trace.Write(
                            "Exception : " + ex.Message,
                            ALTRACE.DEBUG);
                        lock (m_listeMessagesATraiter)
                        {
                            m_listeMessagesATraiter.InsertRange(0, lstMessages);
                        }
                        break;
                    }
                    TimeSpan sp = DateTime.Now - dtChrono;
                    if (m_nNbMessages % 100 == 0)
                    {
                        Console.WriteLine("Traite alrm (" + m_nNbMessages + "): " + sp.TotalMilliseconds);
                    }
                }
            }
            m_gestionnaireAlarmes.SendAlarmes();
        }
Esempio n. 16
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();
            }
        }
Esempio n. 17
0
        public static void Main(string[] args)
        {
            IPAddress address = args.Length == 1 ? IPAddress.Parse(args[0]) : IPAddress.Loopback;

            Messenger.SendTrapV1(
                new IPEndPoint(address, 162),
                IPAddress.Loopback,
                new OctetString("public"),
                new ObjectIdentifier(new uint[] { 1, 3, 6 }),
                GenericCode.ColdStart,
                0,
                0,
                new List <Variable>());

            //Thread.Sleep(50);


            Messenger.SendTrapV2(
                0,
                VersionCode.V2,
                new IPEndPoint(address, 162),
                new OctetString("public"),
                new ObjectIdentifier(new uint[] { 1, 3, 6 }),
                0,
                new List <Variable>());
            //Thread.Sleep(50);

            try
            {
                Messenger.SendInform(
                    0,
                    VersionCode.V2,
                    new IPEndPoint(address, 162),
                    new OctetString("public"),
                    new ObjectIdentifier(new uint[] { 1, 3, 6 }),
                    0,
                    new List <Variable>(),
                    2000,
                    null,
                    null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            try
            {
                Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.InformRequestPdu);
                ReportMessage report    = discovery.GetResponse(2000, new IPEndPoint(address, 162));

                Messenger.SendInform(
                    0,
                    VersionCode.V3,
                    new IPEndPoint(address, 162),
                    new OctetString("neither"),
                    new ObjectIdentifier(new uint[] { 1, 3, 6 }),
                    0,
                    new List <Variable>(),
                    2000,
                    DefaultPrivacyProvider.DefaultPair,
                    report);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            {
                var trap = new TrapV2Message(
                    VersionCode.V3,
                    528732060,
                    1905687779,
                    new OctetString("neither"),
                    new ObjectIdentifier("1.3.6"),
                    0,
                    new List <Variable>(),
                    DefaultPrivacyProvider.DefaultPair,
                    0x10000,
                    new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449")),
                    0,
                    0);
                trap.Send(new IPEndPoint(address, 162));
            }

            {
#if NET452
                var trap = new TrapV2Message(
                    VersionCode.V3,
                    528732060,
                    1905687779,
                    new OctetString("privacy"),
                    new ObjectIdentifier("1.3.6"),
                    0,
                    new List <Variable>(),
                    new DESPrivacyProvider(
                        new OctetString("privacyphrase"),
                        new MD5AuthenticationProvider(new OctetString("authentication"))),
                    0x10000,
                    new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449")),
                    0,
                    0);
                trap.Send(new IPEndPoint(address, 162));
#endif
            }
        }
Esempio n. 18
0
        //-----------------------------------------------
        public static CTrapInstance FromMessage(
            ISnmpMessage message,
            CAgentSnmpPourSupervision agentPourSupervision)
        {
            TrapV1Message        trapV1 = message as TrapV1Message;
            TrapV2Message        trapV2 = message as TrapV2Message;
            InformRequestMessage inform = message as InformRequestMessage;

            if (trapV1 != null)
            {
                CInterrogateurSnmp agent = new CInterrogateurSnmp();
                agent.ConnexionIp        = trapV1.AgentAddress.ToString();
                agent.Connexion.Version  = trapV1.Version;
                agent.ConnexionCommunity = trapV1.Community.ToString();
                agent.ConnexionPort      = 161;
                if (agentPourSupervision != null && agentPourSupervision.TypeAgent != null)
                {
                    agentPourSupervision.TypeAgent.PrepareDynamicSnmpAgent(agent);
                }

                CTrapInstance instance = new CTrapInstance(agent);
                instance.m_strEntreprise = trapV1.Enterprise.ToString();
                instance.m_version       = trapV1.Version;
                instance.m_strAgentIP    = trapV1.AgentAddress.ToString();
                instance.m_strCommunity  = trapV1.Community.ToString();
                instance.GenericCode     = trapV1.Generic;
                instance.SpecificValue   = trapV1.Specific.ToString();
                instance.AgentSnmp       = agentPourSupervision;
                foreach (Variable variable in trapV1.Variables())
                {
                    CTrapFieldValueBrute valeur = new CTrapFieldValueBrute(variable.Id.ToString(), variable.Data.ToString());
                    instance.AddValue(valeur);
                }
                return(instance);
            }
            else if (trapV2 != null)
            {
                CInterrogateurSnmp agent = new CInterrogateurSnmp();
                if (trapV2.SenderIP == null)
                {
                    return(null);
                }
                agent.ConnexionIp       = trapV2.SenderIP.ToString();
                agent.Connexion.Version = trapV2.Version;
                string strCommunauté = "";
                if (trapV2.Parameters != null)
                {
                    if (trapV2.Parameters.UserName != null)
                    {
                        strCommunauté = trapV2.Parameters.UserName.ToString();
                    }
                }
                agent.ConnexionCommunity = strCommunauté;
                agent.ConnexionPort      = 161;
                if (agentPourSupervision != null && agentPourSupervision.TypeAgent != null)
                {
                    agentPourSupervision.TypeAgent.PrepareDynamicSnmpAgent(agent);
                }

                CTrapInstance instance = new CTrapInstance(agent);
                instance.m_strEntreprise = trapV2.Enterprise.ToString();
                instance.m_strAgentIP    = trapV2.SenderIP.ToString();
                instance.m_version       = trapV2.Version;
                instance.m_strCommunity  = strCommunauté;
                if (trapV2.Enterprise.ToString() == ".1.3.6.1.6.3.1.1.5.1")
                {
                    instance.GenericCode = GenericCode.ColdStart;
                }
                else if (trapV2.Enterprise.ToString() == ".1.3.6.1.6.3.1.1.5.2")
                {
                    instance.GenericCode = GenericCode.WarmStart;
                }
                else if (trapV2.Enterprise.ToString() == ".1.3.6.1.6.3.1.1.5.3")
                {
                    instance.GenericCode = GenericCode.LinkDown;
                }
                else if (trapV2.Enterprise.ToString() == ".1.3.6.1.6.3.1.1.5.4")
                {
                    instance.GenericCode = GenericCode.LinkUp;
                }
                else if (trapV2.Enterprise.ToString() == ".1.3.6.1.6.3.1.1.5.5")
                {
                    instance.GenericCode = GenericCode.AuthenticationFailure;
                }
                else if (trapV2.Enterprise.ToString() == ".1.3.6.1.6.3.1.1.5.6")
                {
                    instance.GenericCode = GenericCode.EgpNeighborLoss;
                }
                else
                {
                    instance.GenericCode = GenericCode.EnterpriseSpecific;
                    int nPos = instance.m_strEntreprise.LastIndexOf(".");
                    if (nPos >= 0)
                    {
                        instance.m_strSpecific   = instance.m_strEntreprise.Substring(nPos + 1);
                        instance.m_strEntreprise = instance.m_strEntreprise.Substring(0, nPos);
                    }
                }
                instance.AgentSnmp = agentPourSupervision;
                foreach (Variable variable in trapV2.Variables())
                {
                    CTrapFieldValueBrute valeur = new CTrapFieldValueBrute(variable.Id.ToString(), variable.Data.ToString());
                    instance.AddValue(valeur);
                }
                return(instance);
            }
            return(null);
        }
Esempio n. 19
0
        /// <summary>
        /// Invio effettivo TRAP
        /// </summary>
        /// <param name="id">Identificativo oggetto</param>
        /// <param name="variables">Elenco parametri da inviare</param>
        /// <returns></returns>
        public bool SendTrap(string id, List <Variable> variables)
        {
            bool success = false;



            try
            {
                switch (myVersion)
                {
                case "V1":     // Lextm.SharpSnmpLib.VersionCode.V1:
                    Messenger.SendTrapV1(
                        new IPEndPoint(IpRequestManager, IpRequestPORT),
                        IpRequestSender,
                        UName,
                        new ObjectIdentifier(id),
                        GenericCode.ColdStart,
                        0,      //specific
                        0,      //timestamp
                        variables
                        );

                    break;

                case "V2":     // Lextm.SharpSnmpLib.VersionCode.V2:

                    Messenger.SendTrapV2(
                        0,          //request Id
                        Lextm.SharpSnmpLib.VersionCode.V2,
                        new IPEndPoint(IpRequestManager, IpRequestPORT),
                        UName,
                        new ObjectIdentifier(id),
                        0,          //timestamp
                        variables
                        );

                    //var trap = new TrapV2Message(
                    //  VersionCode.V3,
                    //  1,
                    //  1,
                    //  UName,
                    //  new ObjectIdentifier(id),
                    //  0,
                    //  variables,
                    //  DefaultPrivacyProvider.DefaultPair,
                    //  0x10000,
                    //  new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449")),
                    //  0,
                    //  0);

                    //trap.Send(new IPEndPoint(IpRequestManager, IpRequestPORT));
                    break;

                case "V3":     // Lextm.SharpSnmpLib.VersionCode.V3:

                    var trap = new TrapV2Message(
                        Lextm.SharpSnmpLib.VersionCode.V3,
                        528732060,          //messageId
                        1905687779,         //request Id
                        UName,
                        new ObjectIdentifier(id),
                        0,                  //time
                        variables,
                        DefaultPrivacyProvider.DefaultPair,
                        0x10000,                                                         //MaxMessageSize
                        new OctetString(ByteTool.Convert("80001F8880E9630000D61FF449")), //Engine id
                        0,                                                               //engine boots
                        0);                                                              //engine time

                    trap.Send(new IPEndPoint(IpRequestManager, IpRequestPORT));

                    break;
                }

                success = true;
            }
            catch (Exception ex)
            {
                ErrorString = String.Format("Message: {0}\r\nSource: {1}\r\nStackTrace:{2}", ex.Message, ex.Source, ex.StackTrace);
            }

            return(success);
        }