public void TestConstructor()
 {
     var response = new ResponseMessage(
         VersionCode.V3,
         new Header(
             new Integer32(500),
             new Integer32(4000),
             Levels.Reportable),
         new SecurityParameters(
             OctetString.Empty,
             Integer32.Zero,
             Integer32.Zero,
             new OctetString("lextm"),
             OctetString.Empty,
             OctetString.Empty),
         new Scope(
             OctetString.Empty,
             OctetString.Empty,
             new ResponsePdu(0x2C6B, ErrorCode.NoError, 0, new List<Variable>{ new Variable(new ObjectIdentifier("1.3.6.1.1.2.5.0"), new Integer32(400))})),
         DefaultPrivacyProvider.DefaultPair,
         true,
         null);
     var registry = new UserRegistry();
     registry.Add(new OctetString("lextm"), DefaultPrivacyProvider.DefaultPair);
     var messages = MessageFactory.ParseMessages(response.ToBytes(), registry);
     Assert.AreEqual(1, messages.Count);
 }
Exemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SnmpContextBase"/> class.
 /// </summary>
 /// <param name="request">The request.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="users">The users.</param>
 /// <param name="group">The engine core group.</param>
 /// <param name="binding">The binding.</param>
 protected SnmpContextBase(ISnmpMessage request, IPEndPoint sender, UserRegistry users, EngineGroup group, IListenerBinding binding)
 {
     Request = request;
     Binding = binding;
     Users = users;
     Sender = sender;
     CreatedTime = DateTime.Now;
     Group = group;
 }
        /// <summary>
        /// Creates the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="sender">The sender.</param>
        /// <param name="users">The users.</param>
        /// <param name="group">The engine group.</param>
        /// <param name="binding">The binding.</param>
        /// <returns></returns>
        public static SnmpContext Create(ISnmpMessage request, IPEndPoint sender, UserRegistry users, EngineGroup group, IListenerBinding binding)
        {
            if (request.Version == VersionCode.V3)
            {
                return new SecureSnmpContext(request, sender, users, group, binding);
            }

            return new NormalSnmpContext(request, sender, users, binding);
        }
Exemplo n.º 4
0
 /// <summary>
 /// Creates <see cref="ISnmpMessage"/> instances from a string.
 /// </summary>
 /// <param name="bytes">Byte string.</param>
 /// <param name="registry">The registry.</param>
 /// <returns></returns>
 public static IList<ISnmpMessage> ParseMessages(IEnumerable<char> bytes, UserRegistry registry)
 {
     if (bytes == null)
     {
         throw new ArgumentNullException("bytes");
     }
     
     if (registry == null)
     {
         throw new ArgumentNullException("registry");
     }
     
     return ParseMessages(ByteTool.Convert(bytes), registry);
 }
Exemplo n.º 5
0
        /// <summary>
        /// Creates <see cref="ISnmpMessage"/> instances from buffer.
        /// </summary>
        /// <param name="buffer">Buffer.</param>
        /// <param name="registry">The registry.</param>
        /// <returns></returns>
        public static IList<ISnmpMessage> ParseMessages(byte[] buffer, UserRegistry registry)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

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

            return ParseMessages(buffer, 0, buffer.Length, registry);
        }
 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.AreEqual(1, messages.Count);
     var message = messages[0];
     Assert.AreEqual(1, message.Variables().Count);
     Assert.AreEqual("not in time window", message.Variables()[0].Id.GetErrorMessage());
 }
Exemplo n.º 7
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);
            }
        }
Exemplo n.º 8
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"))));
            users.Add(new OctetString("privacy"), new DESPrivacyProvider(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 http://sharpsnmplib.codeplex.com");
                Console.WriteLine("Press any key to stop . . . ");
                Console.Read();
                engine.Stop();
            }
        }
Exemplo n.º 9
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 TestReportFailure()
        {
            const string data = "30 70 02 01 03 30"+
                                "11 02 04 76 EB 6A 22 02 03 00 FF F0 04 01 01 02 01 03 04 33 30 31 04 09"+

                                "80 00 05 23 01 C1 4D BB 83 02 01 5B 02 03 1C 93 9D 04 0C 4D 44 35 5F 44"+
                                "45 53 5F 55 73 65 72 04 0C E5 C7 C5 2E 17 7E 87 62 AB 56 D6 C7 04 00 30"+
                                "23 04 00 04 00 A8 1D 02 01 00 02 01 00 02 01 00 30 12 30 10 06 0A 2B 06"+

                                "01 06 03 0F 01 01 02 00 41 02 05 EE";
            var bytes = ByteTool.Convert(data);
            const string userName = "******";
            const string phrase = "AuthPassword";
            const string privatePhrase = "PrivPassword";
            IAuthenticationProvider auth = new MD5AuthenticationProvider(new OctetString(phrase));
            IPrivacyProvider priv = new DESPrivacyProvider(new OctetString(privatePhrase), auth);
            var users = new UserRegistry();
            users.Add(new User(new OctetString(userName), priv));
            var messages = MessageFactory.ParseMessages(bytes, users);
            Assert.AreEqual(1, messages.Count);
            var message = messages[0];
            Assert.AreEqual(1, message.Variables().Count);
        }
Exemplo n.º 11
0
        public SecureAgentProfile(Guid id, VersionCode version, IPEndPoint agent, string agentName, string authenticationPassphrase, string privacyPassphrase, int authenticationMethod, int privacyMethod, string userName, int timeout)
            : base(id, version, agent, agentName, userName, timeout)
        {
            AuthenticationPassphrase = authenticationPassphrase;
            PrivacyPassphrase = privacyPassphrase;
            AuthenticationMethod = authenticationMethod;
            PrivacyMethod = privacyMethod;

            switch (AuthenticationMethod)
            {
                case 0:
                    _auth = DefaultAuthenticationProvider.Instance;
                    break;
                case 1:
                    _auth = new MD5AuthenticationProvider(new OctetString(AuthenticationPassphrase));
                    break;
                case 2:
                    _auth = new SHA1AuthenticationProvider(new OctetString(AuthenticationPassphrase));
                    break;
            }

            switch (PrivacyMethod)
            {
                case 0:
                    _privacy = new DefaultPrivacyProvider(_auth);
                    break;
                case 1:
                    _privacy = new DESPrivacyProvider(new OctetString(PrivacyPassphrase), _auth);
                    break;
                case 2:
                    _privacy = new AESPrivacyProvider(new OctetString(PrivacyPassphrase), _auth);
                    break;
            }
            
            _registry = new UserRegistry().Add(new OctetString(userName), _privacy);
        }
 public SnmpMessageAsyncResult(IAsyncResult inner, Socket socket, UserRegistry users, IPEndPoint receiver, byte[] buffer)
 {
     _buffer = buffer;
     WorkSocket = socket;
     Users = users;
     Receiver = receiver;
     Inner = inner;
 }
Exemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SecureSnmpContext"/> class.
 /// </summary>
 /// <param name="request">The request.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="users">The users.</param>
 /// <param name="group">The engine core group.</param>
 /// <param name="binding">The binding.</param>
 public SecureSnmpContext(ISnmpMessage request, IPEndPoint sender, UserRegistry users, EngineGroup group, IListenerBinding binding)
     : base(request, sender, users, group, binding)
 {
 }
        /// <summary>
        /// Sends an  <see cref="ISnmpMessage"/> and handles the response from agent.
        /// </summary>
        /// <param name="request">The <see cref="ISnmpMessage"/>.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="receiver">Agent.</param>
        /// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
        /// <param name="registry">The user registry.</param>
        /// <returns></returns>
        public static ISnmpMessage GetResponse(this ISnmpMessage request, int timeout, IPEndPoint receiver, UserRegistry registry, Socket udpSocket)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

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

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

            var requestCode = request.TypeCode();
            if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode));
            }

            var bytes = request.ToBytes();
            #if CF
            int bufSize = 8192;
            #else
            var bufSize = udpSocket.ReceiveBufferSize;
            #endif
            var reply = new byte[bufSize];

            // Whatever you change, try to keep the Send and the Receive close to each other.
            udpSocket.SendTo(bytes, receiver);
            #if !CF
            udpSocket.ReceiveTimeout = timeout;
            #endif
            int count;
            try
            {
                count = udpSocket.Receive(reply, 0, bufSize, SocketFlags.None);
            }
            catch (SocketException ex)
            {
                // FIXME: If you use a Mono build without the fix for this issue (https://bugzilla.novell.com/show_bug.cgi?id=599488), please uncomment this code.
                /*
                if (SnmpMessageExtension.IsRunningOnMono && ex.ErrorCode == 10035)
                {
                    throw TimeoutException.Create(receiver.Address, timeout);
                }
                // */

                if (ex.ErrorCode == WSAETIMEDOUT)
                {
                    throw TimeoutException.Create(receiver.Address, timeout);
                }

                throw;
            }

            // Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid an issue if parsing >1 response).
            var response = MessageFactory.ParseMessages(reply, 0, count, registry)[0];
            var responseCode = response.TypeCode();
            if (responseCode == SnmpType.ResponsePdu || responseCode == SnmpType.ReportPdu)
            {
                var requestId = request.MessageId();
                var responseId = response.MessageId();
                if (responseId != requestId)
                {
                    throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", requestId, responseId), receiver.Address);
                }

                return response;
            }

            throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", responseCode), receiver.Address);
        }
        /// <summary>
        /// Begins to asynchronously send an <see cref="ISnmpMessage"/> to an <see cref="IPEndPoint"/>.
        /// </summary>
        /// <param name="request">The <see cref="ISnmpMessage"/>.</param>
        /// <param name="receiver">Agent.</param>
        /// <param name="registry">The user registry.</param>
        /// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
        /// <param name="callback">The callback.</param>
        /// <param name="state">The state object.</param>
        /// <returns></returns>
        public static IAsyncResult BeginGetResponse(this ISnmpMessage request, IPEndPoint receiver, UserRegistry registry, Socket udpSocket, AsyncCallback callback, object state)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

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

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

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

            var requestCode = request.TypeCode();
            if (requestCode == SnmpType.TrapV1Pdu || requestCode == SnmpType.TrapV2Pdu || requestCode == SnmpType.ReportPdu)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", requestCode));
            }

            // Whatever you change, try to keep the Send and the Receive close to each other.
            udpSocket.SendTo(request.ToBytes(), receiver);
            #if CF
            var bufferSize = 8192;
            #else
            var bufferSize = udpSocket.ReceiveBufferSize;
            #endif
            var buffer = new byte[bufferSize];

            // http://sharpsnmplib.codeplex.com/workitem/7234
            if (callback != null)
            {
                AsyncCallback wrapped = callback;
                callback = asyncResult =>
                {
                    var result = new SnmpMessageAsyncResult(asyncResult, udpSocket, registry, receiver, buffer);
                    wrapped(result);
                };
            }

            var ar = udpSocket.BeginReceive(buffer, 0, bufferSize, SocketFlags.None, callback, state);
            return new SnmpMessageAsyncResult(ar, udpSocket, registry, receiver, buffer);
        }
        /// <summary>
        /// Sends this <see cref="SetRequestMessage"/> and handles the response from agent.
        /// </summary>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="receiver">Agent.</param>
        /// <param name="socket">The UDP <see cref="Socket"/> to use to send/receive.</param>
        /// <returns></returns>
        private ISnmpMessage GetResponse(int timeout, IPEndPoint receiver, Socket socket)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }
            
            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }

            UserRegistry registry = new UserRegistry();
            if (Version == VersionCode.V3)
            {
                registry.Add(Parameters.UserName, Privacy);
            }

            return MessageFactory.GetResponse(receiver, ToBytes(), MessageId, timeout, registry, socket);
        }
        /// <summary>
        /// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
        /// </summary>
        /// <param name="request">The <see cref="ISnmpMessage"/>.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="receiver">Agent.</param>
        /// <param name="udpSocket">The UDP <see cref="Socket"/> to use to send/receive.</param>
        /// <returns></returns>
        public static ISnmpMessage GetResponse(this ISnmpMessage request, int timeout, IPEndPoint receiver, Socket udpSocket)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            
            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }
            
            if (udpSocket == null)
            {
                throw new ArgumentNullException("udpSocket");
            }
            
            var registry = new UserRegistry();
            if (request.Version == VersionCode.V3)
            {
                registry.Add(request.Parameters.UserName, request.Privacy);
            }

            return request.GetResponse(timeout, receiver, registry, udpSocket);
        }
Exemplo n.º 18
0
		/// <summary>
		/// Sends an SNMP message and wait for its responses.
		/// </summary>
		/// <param name="receiver">The IP address and port of the target to talk to.</param>
		/// <param name="bytes">The byte array representing the SNMP message.</param>
		/// <param name="number">The <see cref="ResponseMessage.MessageId"/> of the SNMP message.</param>
		/// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
		/// <param name="registry">The registry.</param>
		/// <param name="socket">The UDP <see cref="Socket"/> to use to send/receive.</param>
		/// <returns>
		/// The response message (<see cref="ISnmpMessage"/>).
		/// </returns>
		/// <exception cref="TimeoutException">Timeout happens.</exception>
		internal static ISnmpMessage GetResponse(IPEndPoint receiver, byte[] bytes, int number, int timeout, UserRegistry registry, Socket socket)
		{
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}

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

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

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

#if CF
			int bufSize = 8192;
#else
			int bufSize = socket.ReceiveBufferSize;
#endif
			byte[] reply = new byte[bufSize];

			// Whatever you change, try to keep the Send and the Receive close to each other.
#if ! SILVERLIGHT  //mc++
			socket.SendTo(bytes, receiver);
#endif //mc++
#if ! SILVERLIGHT  //mc++
#if !(CF)
			socket.ReceiveTimeout = timeout;
#endif
#endif // mc++
			int count = 0;	//mc++

			try
			{
#if ! SILVERLIGHT  //mc++
				count = socket.Receive(reply, 0, bufSize, SocketFlags.None);
#endif
			}
			catch (SocketException ex)
			{
				// FIXME: If you use a Mono build without the fix for this bug (https://bugzilla.novell.com/show_bug.cgi?id=599488), please uncomment this code.
				//if (SnmpMessageExtension.IsRunningOnMono && ex.ErrorCode == 10035)
				//{
				//    throw TimeoutException.Create(receiver.Address, timeout);
				//}

				if (ex.ErrorCode == WSAETIMEDOUT)
				{
					throw TimeoutException.Create(receiver.Address, timeout);
				}

				throw;
			}

			// Passing 'count' is not necessary because ParseMessages should ignore it, but it offer extra safety (and would avoid a bug if parsing >1 response).
			ISnmpMessage message = ParseMessages(reply, 0, count, registry)[0];
			var code = message.Pdu.TypeCode;
			if (code == SnmpType.ResponsePdu || code == SnmpType.ReportPdu)
			{
				var id = message.MessageId;
				if (id != number)
				{
					throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response sequence: expected {0}, received {1}", number, id), receiver.Address);
				}

				return message;
			}

			throw OperationException.Create(string.Format(CultureInfo.InvariantCulture, "wrong response type: {0}", code), receiver.Address);
		}
 public void TestTrapV3Auth()
 {
     byte[] bytes = Resources.trapv3auth;
     UserRegistry registry = new UserRegistry();
     registry.Add(new OctetString("lextm"), new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication"))));
     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("84433969457707152C289A3E", message.Parameters.AuthenticationParameters.ToHexString());
     Assert.AreEqual("", message.Parameters.PrivacyParameters.ToHexString());
     Assert.AreEqual("", message.Scope.ContextEngineId.ToHexString()); // SNMP#NET returns string.Empty here.
     Assert.AreEqual("", message.Scope.ContextName.ToHexString());
     Assert.AreEqual(318463383, message.MessageId);
     Assert.AreEqual(1276263065, message.RequestId);
 }
Exemplo n.º 20
0
		/// <summary>
		/// Creates <see cref="ISnmpMessage"/> instances from buffer.
		/// </summary>
		/// <param name="buffer">Buffer.</param>
		/// <param name="index">The index.</param>
		/// <param name="length">The length.</param>
		/// <param name="registry">The registry.</param>
		/// <returns></returns>
		public static IList<ISnmpMessage> ParseMessages(byte[] buffer, int index, int length, UserRegistry registry)
		{
			if (registry == null)
			{
				throw new ArgumentNullException("registry");
			}

			if (buffer == null)
			{
				throw new ArgumentNullException("buffer");
			}
			
			IList<ISnmpMessage> result = new List<ISnmpMessage>();
			using (Stream stream = new MemoryStream(buffer, index, length, false))
			{                
				int first;
				while ((first = stream.ReadByte()) != -1)
				{
					ISnmpMessage message = ParseMessage(first, stream, registry);
					if (message == null)
					{
						continue;
					}
	
					result.Add(message);
				}
			}

			return result;
		}
Exemplo n.º 21
0
		private static ISnmpMessage ParseMessage(int first, Stream stream, UserRegistry registry)
		{
			ISnmpData array = DataFactory.CreateSnmpData(first, stream);
			if (array == null)
			{
				return null;
			}

			if (array.TypeCode != SnmpType.Sequence)
			{
				throw new SnmpException("not an SNMP message");
			}

			Sequence body = (Sequence)array;
			if (body.Count != 3 && body.Count != 4)
			{
				throw new SnmpException("not an SNMP message");
			}

			VersionCode version = (VersionCode)((Integer32)body[0]).ToInt32();
			Header header;
			SecurityParameters parameters;
			IPrivacyProvider privacy;
			Scope scope;
			if (body.Count == 3)
			{
				header = Header.Empty;
				parameters = new SecurityParameters(null, null, null, (OctetString)body[1], null, null);
				privacy = DefaultPrivacyProvider.DefaultPair;                
				scope = new Scope((ISnmpPdu)body[2]);
			}
			else
			{
				header = new Header(body[1]);
				parameters = new SecurityParameters((OctetString)body[2]);
				privacy = registry.Find(parameters.UserName);
				if (privacy == null)
				{
					// handle decryption exception.
					return new MalformedMessage(header.MessageId, parameters.UserName);
				}

				var code = body[3].TypeCode;
				if (code == SnmpType.Sequence)
				{
					// v3 not encrypted
					scope = new Scope((Sequence)body[3]);
				}
				else if (code == SnmpType.OctetString)
				{
					// v3 encrypted
					try
					{
						scope = new Scope((Sequence)privacy.Decrypt(body[3], parameters));
					}
					catch (DecryptionException)
					{
						// handle decryption exception.
						return new MalformedMessage(header.MessageId, parameters.UserName);
					}
				}
				else
				{
					throw new SnmpException(string.Format(CultureInfo.InvariantCulture, "invalid v3 packets scoped data: {0}", code));
				}

				if (!privacy.AuthenticationProvider.VerifyHash(version, header, parameters, body[3], privacy))
				{
					throw new SnmpException("invalid v3 packet data");
				}
			}

			var scopeCode = scope.Pdu.TypeCode;
			switch (scopeCode)
			{
				case SnmpType.TrapV1Pdu:
					return new TrapV1Message(body);
				case SnmpType.TrapV2Pdu:
					return new TrapV2Message(version, header, parameters, scope, privacy);
				case SnmpType.GetRequestPdu:
					return new GetRequestMessage(version, header, parameters, scope, privacy);
				case SnmpType.ResponsePdu:
					return new ResponseMessage(version, header, parameters, scope, privacy, false);
				case SnmpType.SetRequestPdu:
					return new SetRequestMessage(version, header, parameters, scope, privacy);
				case SnmpType.GetNextRequestPdu:
					return new GetNextRequestMessage(version, header, parameters, scope, privacy);
				case SnmpType.GetBulkRequestPdu:
					return new GetBulkRequestMessage(version, header, parameters, scope, privacy);
				case SnmpType.ReportPdu:
					return new ReportMessage(version, header, parameters, scope, privacy);
				case SnmpType.InformRequestPdu:
					return new InformRequestMessage(version, header, parameters, scope, privacy);
				default:
					throw new SnmpException(string.Format(CultureInfo.InvariantCulture, "unsupported pdu: {0}", scopeCode));
			}
		}
 public void TestGetV3()
 {
     const string bytes = "30 68 02 01  03 30 0F 02  02 6A 08 02  03 00 FF E3" +
                          "04 01 04 02  01 03 04 23  30 21 04 0D  80 00 1F 88" +
                          "80 E9 63 00  00 D6 1F F4  49 02 01 05  02 02 0F 1B" +
                          "04 05 6C 65  78 74 6D 04  00 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 2C 6A  02 01 00 02  01 00 30 0E  30 0C 06 08" +
                          "2B 06 01 02  01 01 03 00  05 00";
     UserRegistry registry = new UserRegistry();
     registry.Add(new OctetString("lextm"), DefaultPrivacyProvider.DefaultPair);
     IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, registry);
     Assert.AreEqual(1, messages.Count);
     GetRequestMessage get = (GetRequestMessage)messages[0];
     Assert.AreEqual(27144, get.MessageId);
     //Assert.AreEqual(SecurityLevel.None | SecurityLevel.Reportable, get.Level);
     Assert.AreEqual("lextm", get.Community.ToString());
 }
        public void TestGetRequestV3AuthPriv()
        {
            const string bytes = "30 81 80 02  01 03 30 0F  02 02 6C 99  02 03 00 FF" +
                                 "E3 04 01 07  02 01 03 04  38 30 36 04  0D 80 00 1F" +
                                 "88 80 E9 63  00 00 D6 1F  F4 49 02 01  14 02 01 35" +
                                 "04 07 6C 65  78 6D 61 72  6B 04 0C 80  50 D9 A1 E7" +
                                 "81 B6 19 80  4F 06 C0 04  08 00 00 00  01 44 2C A3" +
                                 "B5 04 30 4B  4F 10 3B 73  E1 E4 BD 91  32 1B CB 41" +
                                 "1B A1 C1 D1  1D 2D B7 84  16 CA 41 BF  B3 62 83 C4" +
                                 "29 C5 A4 BC  32 DA 2E C7  65 A5 3D 71  06 3C 5B 56" +
                                 "FB 04 A4";
            MD5AuthenticationProvider auth = new MD5AuthenticationProvider(new OctetString("testpass"));
            var registry = new UserRegistry();
            registry.Add(new OctetString("lexmark"), new DESPrivacyProvider(new OctetString("passtest"), auth));
            IList<ISnmpMessage> messages = MessageFactory.ParseMessages(bytes, registry);
            Assert.AreEqual(1, messages.Count);
            GetRequestMessage get = (GetRequestMessage)messages[0];
            Assert.AreEqual(27801, get.MessageId);
            //Assert.AreEqual(SecurityLevel.None | SecurityLevel.Reportable, get.Level);
            Assert.AreEqual("lexmark", get.Community.ToString());
            //OctetString digest = new MD5AuthenticationProvider(new OctetString("testpass")).ComputeHash(get);

            //Assert.AreEqual(digest, get.Parameters.AuthenticationParameters);
        }
Exemplo n.º 24
0
 public void TestTimeOutAsync()
 {
     // IMPORTANT: this test case requires a local SNMP agent such as 
     //   #SNMP Agent (snmpd), 
     //   Windows SNMP agent service, 
     //   Net-SNMP agent, or 
     //   snmp4j agent.
     Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     GetRequestMessage message = new GetRequestMessage(0x4bed, VersionCode.V2, new OctetString("public"), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) });
     
     var users = new UserRegistry();
     var ar2 = message.BeginGetResponse(new IPEndPoint(IPAddress.Loopback, 161), users, socket, null, null);
     var response = message.EndGetResponse(ar2);
     Assert.AreEqual(SnmpType.ResponsePdu, response.TypeCode());
 }
 public void TestTrapV3AuthPriv()
 {
     // The message body generated by snmp#net is problematic.
     byte[] bytes = Resources.trapv3authpriv;
     string line = ByteTool.Convert(bytes);
     UserRegistry registry = new UserRegistry();
     registry.Add(new OctetString("lextm"), new DESPrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
     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("89D351891A55829243617F2C", 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);
 }
Exemplo n.º 26
0
		/// <summary>
		/// Initializes a new instance of the <see cref="ListenerBinding"/> class.
		/// </summary>
		/// <param name="users">The users.</param>
		/// <param name="adapters">The adapters.</param>
		/// <param name="endpoint">The endpoint.</param>
		public ListenerBinding(UserRegistry users, IEnumerable<IListenerAdapter> adapters, IPEndPoint endpoint)
		{
			_users = users;
			Endpoint = endpoint;
			_adapters = adapters;
		}
Exemplo n.º 27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NormalSnmpContext"/> class.
 /// </summary>
 /// <param name="request">The request.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="users">The users.</param>
 /// <param name="binding">The binding.</param>
 public NormalSnmpContext(ISnmpMessage request, IPEndPoint sender, UserRegistry users, IListenerBinding binding) 
     : base(request, sender, users, null, binding)
 {
 }
        /// <summary>
        /// Sends this <see cref="ISnmpMessage"/> and handles the response from agent.
        /// </summary>
        /// <param name="request">The <see cref="ISnmpMessage"/>.</param>
        /// <param name="timeout">The time-out value, in milliseconds. The default value is 0, which indicates an infinite time-out period. Specifying -1 also indicates an infinite time-out period.</param>
        /// <param name="receiver">Port number.</param>
        /// <param name="registry">User registry.</param>
        /// <returns></returns>
        public static ISnmpMessage GetResponse(this ISnmpMessage request, int timeout, IPEndPoint receiver, UserRegistry registry)
        {
            // TODO: make more usage of UserRegistry.
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

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

            var code = request.TypeCode();
            if (code == SnmpType.TrapV1Pdu || code == SnmpType.TrapV2Pdu || code == SnmpType.ReportPdu)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "not a request message: {0}", code));
            }
            
            using (var socket = receiver.GetSocket())
            {
                return request.GetResponse(timeout, receiver, registry, socket);
            }
        }
Exemplo n.º 29
0
        public MainForm()
        {
            // TODO: this is a hack. review it later.
            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"))));
            users.Add(new OctetString("privacy"), new DESPrivacyProvider(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(new RollingLogger(), store, membership, handlerFactory);
            _engine = new SnmpEngine(pipelineFactory, new Listener { Users = users }, new EngineGroup());
            _engine.ExceptionRaised += (sender, e) => MessageBox.Show(e.Exception.ToString());

            InitializeComponent();
            if (PlatformSupport.Platform == PlatformType.Windows)
            {
                // FIXME: work around a Mono WinForms issue.
                Icon = Properties.Resources.network_server;                
            }
            
            actEnabled.Image = Properties.Resources.media_playback_start;
            tstxtPort.Text = @"161";
            tscbIP.Items.Add(StrAllUnassigned);
            foreach (IPAddress address in Dns.GetHostEntry(string.Empty).AddressList.Where(address => !address.IsIPv6LinkLocal))
            {
                tscbIP.Items.Add(address);
            }

            tscbIP.SelectedIndex = 0;
        }
Exemplo n.º 30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ListenerBinding"/> class.
 /// </summary>
 /// <param name="users">The users.</param>
 /// <param name="endpoint">The endpoint.</param>
 public ListenerBinding(UserRegistry users, IPEndPoint endpoint)
 {
     _users = users;
     Endpoint = endpoint;
 }