Code Monkey home page Code Monkey logo

sharpsnmplib's Introduction

sharpsnmplib's People

Contributors

aib avatar azure-pipelines[bot] avatar danielkozlowski avatar denis-pakizh avatar geforce-hisa0904 avatar gralin avatar gregmac avatar karlox2 avatar lextm avatar mattzink avatar mrinaldas avatar nn--- avatar quintinon avatar ruhansa079 avatar semihokur avatar sinstr avatar sweetpants avatar vhallac avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sharpsnmplib's Issues

Make Variable class not sealed

Hi!

Would you mind removing the sealed keyword from the Variable class? I would like to store additional properties with it. Also, can you make the setter of the Data property of that class public?

Thanks

GetResponseAsync -> SocketException -> AddressFamilyNotSupported

I found bug what hapening when i invoke many GetBulk requests with one socket. The bug is played only for large (more than 20) number of requests After several successful queries, an SocketException occurs with the AddressFamilyNotSupported.

OS: Win7 64
Framework versrion: 4.5.2
Lib versrion: 10.0.1

Minimal code for reproduce

private async void button3_Click(object sender, EventArgs e)
{
    Task.Run(() => {
        Test();
    });            
}

private async void Test()
{
    IPEndPoint endPoint = new IPEndPoint(new IPAddress(new byte[] { 192, 168, 0, 1}), 161);
    OctetString community = new OctetString("public");

    using (var soc = endPoint.GetSocket()) {
        IList<Variable> varsCache = new List<Variable>(10);

        string colOid = "some.column.oid.of.big.table";
        ObjectIdentifier lastOid = new ObjectIdentifier(colOid);
        while (true) {
            varsCache.Clear();
            varsCache.Add(new Variable(lastOid));
            try {
                var message = new GetBulkRequestMessage(0, VersionCode.V2, community, 0, 20, varsCache);
                var response = await message.GetResponseAsync(endPoint, soc);
                
                var vars = response.Variables();
                foreach (Variable var in vars) {
                    lastOid = var.Id; 
                }

                if (!lastOid.ToString().StartsWith(colOid)) {
                    break;
                }
            }
            catch (SocketException exception) {
                if (exception.SocketErrorCode ==  SocketError.AddressFamilyNotSupported) {
                    throw new Exception("oh");
                }

                throw;
            }
        }

        return;
    }
}

PS:
I found very similar problem https://stackoverflow.com/questions/42579158/uwp-sendtoasync-from-socket-results-in-addressfamilynotsupported

I write quick fix based on SnmpMessageExtension.GetResponseAsync that not using pool for SocketAsyncEventArgs and test my code. And the problem is eliminated.

Fix code(not sure that is correct, only for demo):

public static async Task<ISnmpMessage> GetResponseAsyncFix(ISnmpMessage request, IPEndPoint receiver, Socket udpSocket)
{           
    var bytes = request.ToBytes();
    var bufSize = udpSocket.ReceiveBufferSize = Messenger.MaxMessageSize;
    var registry = new UserRegistry();


    var info = new SocketAsyncEventArgs();
    info.RemoteEndPoint = receiver;
    info.SetBuffer(bytes, 0, bytes.Length);
    using (var awaitable1 = new SocketAwaitable(info)) {
        await udpSocket.SendToAsync(awaitable1);
    }

    int count;
    var reply = new byte[bufSize];
    
    var args = new SocketAsyncEventArgs();
    EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
    try {
        args.RemoteEndPoint = remote;
        args.SetBuffer(reply, 0, bufSize);
        using (var awaitable = new SocketAwaitable(args)) {
            count = await udpSocket.ReceiveAsync(awaitable);
        }
    }
    catch (SocketException ex) 
    {                
        if (ex.SocketErrorCode == SocketError.TimedOut) {
            throw new System.TimeoutException("timeout");
        }

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

        return response;
    }

    throw new Exception("operation");
}

Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

return Numeric(float)

hi, how can i get back Numberic(float)
in ScalarObject

public override ISnmpData Data
        {
            get { return 2.1 }
            set { throw new AccessFailureException(); }
        }

NotInTimeWindow bug

Starting from v 9.0.2 sharp SNMP engine fails to work normally via v3 protocol after 150 seconds of work.
After 150 seconds of work engine starts to return "NotInTimeWindow" instead of normal response.
This was tested for example with Nagios XI, Paessler SNMP tester.

This bug is a very important one, as it makes impossible to use this library for real applications via v3 (150 seconds are of course not enough for that).

Problem is in comparison operator โ€˜>โ€™.
SharpSnmpLib\Pipeline\EngineGroup.cs, Ln116, IsInTime().
Potential problem existed before, but was highly improbable. In 9.0.2 author changed time units from ms to sec and that made this problem very probable, as most of requests are processed within 1 second from time they were sent. Here is the comment and a fix:

        // in previous implementation time was expressed in milliseconds
        // and it was extremely improbable that currentTimeData[1] can be equal to pastTime.
        // therefore there would be no considerable difference between '>' and '>=' below.
        // Now, as time is expressed in seconds, 
        // this is a very typical situation when (currentTimeData[1] == pastTime)
        // and in the case of equality first part of ternary operation should be processed and diff will be 0 and 'true' will be returned.
        // so '>=' should be used here, but not '>'. 
        // (Otherwise, with '>' second part will be used, diff will be -1 and 'false' will be returned.

        // so, we should replace this wrong line:
        //var diff = currentTimeData[1] > pastTime ? currentTimeData[1] - pastTime : currentTimeData[1] - pastTime - int.MinValue + int.MaxValue;

        // with the new one:
        var diff = currentTimeData[1] >= pastTime ? currentTimeData[1] - pastTime : currentTimeData[1] - pastTime - int.MinValue + int.MaxValue;

This implementation was tested with Nagios and Paessler SNMP tester. Everything is okay even after several hours of work (like it was in 9.0.1 and earlier).

BulkWalkAsync infinite loop

The variable "next" is never being updated inside BulkWalkAsync, so you are always looking at the same List of Variables and the same seed, and therefore always seeing that it "has next". You then get stuck in the while loop. In BulkWalk next is an out parameter so it's being updated, but here it's never getting updated.

Make ObjectStore implement IObjectStore

see Issue on codeplex nr Id #7286
https://sharpsnmplib.codeplex.com/workitem/7286

Make ObjectStore inherit from an Interface: IObjectStore, in order to allow customization of the ObjectStore:
https://sharpsnmplib.codeplex.com/SourceControl/latest#SharpSnmpLib/Pipeline/ObjectStore.cs

This is necessary for applications which do not necessarly know all OID's managed by the SNMP Server. The Current Implementation requires knowledge of all OID's on startup/before requesting the Object.

public interface IObjectStore{
public ScalarObject GetObject(ObjectIdentifier id);
public ScalarObject GetNextObject(ObjectIdentifier id);
public void Add(ISnmpObject newObject);
}

ReportMessage has no constructor for creating a new PDU

Hello,
the ReportMessage class (unlike other ..Message classes) seems to have no constructor capable for creating a new PDU. To the only existing constructor one must provide the PDU (scope), which makes sense when deserializing incoming data.

Is that intended?

Thanks

Wrong value in <Version> tag

In the SharpSnmpLib.NetStandard.csproj file, a typo in the <Version> tag prevents compilation.

<Version>9.2.0-
</Version>

Unable to set ContextEngineId or ContextName for SnmpV3 TrapV2Message

Context
I am attempting to migrate away from a closed-source Snmp solution to SharpSnmpLib and I am trying to match our previous output exactly (when it was already correct).

Problem
When using SharpSnmpLib to send SnmpV3 Traps the contextEngineId and contextName are always empty. This was observed in wireshark and seeing that it displayed the contextEngineID as "" and the contextName as "".
This was observed on SharpSnmpLib version 9.0.41121.31 on a Windows 10 x64 machine but the source code on GitHub was inspected and the issue still persists.

Potential Solution
Expose parameters in the SnmpV3 constructor of the TrapV2Message class that allow for ContextEngineId and ContextName to be set when constructing the Scope of the TrapV2Message.

Notes
There is currently a TODO note in the SnmpV3 constructor of the TrapV2Message class where this would need to be changed: https://github.com/lextm/sharpsnmplib/blob/9a297f5151c807a12bdb54bd507a625e8e520c37/SharpSnmpLib/Messaging/TrapV2Message.cs#L149

SnmpMessageExtension.GetReponseAsync throws ArgumentException when response is malformed: truncation error for 32-bit integer coding

This is from the same site where we found #11. A differently malformed SNMP response that hits a different bug (I don't believe it's fixed by #11).

System.AggregateException: One or more errors occurred. ---> System.ArgumentException: truncation error for 32-bit integer coding
Parameter name: length
   at Lextm.SharpSnmpLib.Integer32..ctor(Tuple`2 length, Stream stream)
   at Lextm.SharpSnmpLib.DataFactory.CreateSnmpData(Int32 type, Stream stream)
   at Lextm.SharpSnmpLib.ResponsePdu..ctor(Tuple`2 length, Stream stream)
   at Lextm.SharpSnmpLib.DataFactory.CreateSnmpData(Int32 type, Stream stream)
   at Lextm.SharpSnmpLib.Sequence..ctor(Tuple`2 length, Stream stream)
   at Lextm.SharpSnmpLib.DataFactory.CreateSnmpData(Int32 type, Stream stream)
   at Lextm.SharpSnmpLib.Messaging.MessageFactory.ParseMessage(Int32 first, Stream stream, UserRegistry registry)
   at Lextm.SharpSnmpLib.Messaging.MessageFactory.ParseMessages(Byte[] buffer, Int32 index, Int32 length, UserRegistry registry)
   at Lextm.SharpSnmpLib.Messaging.SnmpMessageExtension.<GetResponseAsync>d__14.MoveNext()

We contact a lot of SNMP servers that are not controlled by us and may or may not be well-behaved so it's important to us that ParseMessage is hardened against malformed responses.

Thanks for all your time and effort on this library.

Problem with v3-Walk

2016-09-26 23-54-48 nagios xi - configuration - mozilla firefox
2016-09-26 23-45-22 nagios xi - configuration - mozilla firefox 2

I've created an SNMP Agent based on the #SNMP Library v9.0.2.
I've found strange behavior concerning v3 Walk.
Please see the screenshots.
Iโ€™ve tested this with Nagios XI.
Get requests are processed correctly for any version of protocol (v1-v3).
Single GetNext is also processed correctly.
Walk under v1 and v2c are also processed correctly.
But there is a problem with Walk under v3 .
Only the first GetNext request is transferred to its handler (GetNextMessageHandler.Handle() ), the next one is ignored by #SNMP library for some reason. Then Nagios tries to request GetNext again several times, does not get any further response and then reports a timeout. engine.ExceptionRaised is not triggered.
So v3 Walk fails.

Paessler SNMP tester can do v3 Walk with #SNMP library. But I see that this tester does this in a different way:

  1. It sends two Get Requests after one GetNext request (one to get UpTime, and another - a value of the object)
  2. It sends three different GetNext requests per object and only one of these requests is processed by the library.

Probably SNMP Tester has better degree of compatibility? Or probably this tester's way of alternation of Get and GetNext makes #SNMP library work better?

Also I've tested Nagios v3-Walk against Power SNMP library. It works correctly. So I suspect that something can be wrong in #SNMP library, or probably it lacks some settings from my side?

Has anybody tested v3-Walk with #SNMP library based agent against Nagios XI or some other popular products?
Do you have ideas about how can we fix v3 Walk with it?

Repeated password string incorrectly passes authentication

For both authentication and privacy checks, i.e. MD5/SHA1 and DES/AES, there is an issue with repeated passwords being incorrectly treated as valid.

E.g. if the password for either is 'password123', if I send a SNMPv3 GET with 'password123password123', it still succeeds.

I've tried changing the algorithms between MD5/SHA1, DES/AES, and they all have the same issue.
I've also tried creating long passwords with many special characters and the issue still persists.

Simple Messenger.Get fails on macOS with System.Net.Sockets.SocketException: Protocol Option not supported

Hello,

when I try to run the following code

var result = Messenger.Get(VersionCode.V1, new IPEndPoint(IPAddress.Parse("192.168.1.2"), 161), new OctetString("public"), new List<Variable>{new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0"))}, 60000);

from https://components.xamarin.com/gettingstarted/sharpsnmplib on my macOS setup, I get the following error: System.Net.Sockets.SocketOptionName 0x13 is not supported at IP level
Here is the Stacktrace:
at System.Net.Sockets.Socket.SetSocketOption (System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, System.Int32 optionValue) [0x00029] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/System/System.Net.Sockets/Socket.cs:2447 \n at System.Net.Sockets.Socket.SetSocketOption (System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, System.Boolean optionValue) [0x00008] in /Users/builder/data/lanes/4992/mono-mac-sdk/external/bockbuild/builds/mono-x64/mcs/class/System/System.Net.Sockets/Socket.cs:2434 \n at Lextm.SharpSnmpLib.Messaging.EndPointExtension.GetSocket (System.Net.EndPoint endpoint) [0x00024] in <1167d5085a7649e2940015ad221eb8f8>:0 \n at Lextm.SharpSnmpLib.Messaging.SnmpMessageExtension.GetResponse (Lextm.SharpSnmpLib.Messaging.ISnmpMessage request, System.Int32 timeout, System.Net.IPEndPoint receiver) [0x00056] in <1167d5085a7649e2940015ad221eb8f8>:0 \n at Lextm.SharpSnmpLib.Messaging.Messenger.Get (Lextm.SharpSnmpLib.VersionCode version, System.Net.IPEndPoint endpoint, Lextm.SharpSnmpLib.OctetString community, System.Collections.Generic.IList1[T] variables, System.Int32 timeout) [0x00052] in <1167d5085a7649e2940015ad221eb8f8>:0 \n at snmptest.MainClass.Main (System.String[] args) [0x0000c] in /Users/chris/Projects/snmptest/snmptest/Program.cs:16 "`

I am running mono 5.4.0.135 on macOS 10.13 Beta (17A306f)

I can provide a sample project if needed. Thanks!

ObjectStore is not easily extendable

The Lextm.SharpSnmpLib.Pipeline.ObjectStore class is difficult to extend because of two problems:

  • The _list field is marked as private.
  • The Add method is not marked as virtual.

This results in either:

  • A derived class needing to use the ObjectStore implementation of Add without being able to change the functionality.
  • A derived class hiding the ObjectStore implementation of Add with the keyword new and then hoping no calls to ObjectStore.Add are made.

I see that an IObjectStore was proposed in #12 / #13 but would cause a lot of code change and instead #14 was implemented which made extending the ObjectStore possible, but not completely feasible.

I propose the following:

  • Changing _list to be protected.
  • Changing Add to be virtual.

What do I do with a Variable?

There is virtually no documentation on the Variable class and what can be done with it. The only real example I see is in the SnmpGet sample

foreach (Variable variable in Messenger.Get(version, receiver, new OctetString(community), vList, timeout)) { Console.WriteLine(variable); }

That's great if I want to write it to the console, but if I want to do a comparison on the returned value I have no way of getting it to an bool/int/string or whatever type corresponds to the returned value;

There are no conversion methods as far as I can tell, I can't use it in any constructors for data types. How do I actually get useful information out the Variable?

Removed most sync API to adapt to .NET Core API

.NET Core API only exposes async methods of Socket class, so that many sync methods in this library today will be obsolete.

It is possible to re-implement them using the async counterparts, but overall async/await style of coding is more suitable in socket programming since .NET 4.5.

error in snmpwalk command with agent

hi
i'm try write a agent with sample code snmpd and define custom Object . but when i use snmpwalk in other library like net-snmp , my agent not return custom Object with value

--custom object

public TestObject()
            : base(new ObjectIdentifier("1.3.6.1.4.1.52222"))
        {
        }
        public override ISnmpData Data
        {
            get
            {
                return new Integer32(12345);
            }

            set
            {
                throw new AccessFailureException();
            }
        }

--my agent

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

other code in my agent is like sample and not change
result command line -> snmpwalk -v 2c -c public 127.0.0.1

SNMPv2-MIB::sysDescr.0 = STRING: #SNMP Agent on Microsoft Windows NT 6.2.9200.0
SNMPv2-MIB::sysObjectID.0 = OID: SNMPv2-SMI::internet
DISMAN-EVENT-MIB::sysUpTimeInstance = Timeticks: (17747798) 2 days, 1:17:57.98
SNMPv2-MIB::sysContact.0 = STRING: Taratech
SNMPv2-MIB::sysName.0 = STRING: DESKTOP-T5PVHIB
SNMPv2-MIB::sysLocation.0 = STRING:

As you can see, the result is not correct and value of TestObject not return
Where is my code wrong?

nuget Dependencies

I am trying to use the nuget package Lextm.SharpSnmpLib in a .NET Framework 4.6.1 project. Installing it will add a reference to SharpSnmpLib.NetStandard with target framework .NETStandard,Version=v1.3. Unless respective nuget packages (e. g. System.Net.Sockets) are installed additionally, executing SharpSnmpLib code will throw "Could not load file or assembly" exceptions for dependencies that are already included in .NET Framework.
Is there a way to fix this?

Windows 10 Trap Issues

I've inherited an application that receives traps and performs certain system actions based on them. It works great on Windows 7/8/Server2008/Server2012. It can send and receive responses to get and set requests but doesn't receive traps on Windows 10.

The app is using .Net 4.0 and SharpSNMP v 8.0.0. I've updated the app to .Net 4.6.1 and SharpSNMP 9.0.5 hoping this was a previously fixed bug with the 8.0 release and Windows 10.

I've used Wireshark to confirm that the SNMP traps are reaching the system. The Windows SNMPTrap service is disabled.

Has anyone else had a similar issue with Windows 10? Is there something that I need to do differently?

Code snippet that sets up the trap listener.

var get = new OctetString("public");
var set = new OctetString("private");
var store = new ObjectStore();

var v1 = new Version1MembershipProvider(get, set);
var v2 = new Version2MembershipProvider(get, set);
var v3 = new Version3MembershipProvider();
var composed = new ComposedMembershipProvider(new IMembershipProvider[] { v1, v2, v3 });

var trapV1Handler = new TrapV1MessageHandler();
var trapV2Handler = new TrapV2MessageHandler();
var informHandler = new InformRequestMessageHandler();
trapV1Handler.MessageReceived += V1MessageHandler_MessageReceived;
trapV2Handler.MessageReceived += V2TrapHandler_MessageReceived;
informHandler.MessageReceived += WatcherInformRequestReceived;

var trapV1 = new HandlerMapping("v1", "TRAPV1", trapV1Handler);
var trapV2 = new HandlerMapping("v2,v3", "TRAPV2", trapV2Handler);
var allV3 = new HandlerMapping("v3", "*", new V3Handler());
var inform = new HandlerMapping("v2", "INFORM", informHandler);
var messageFactory = new MessageHandlerFactory(new[] { trapV1, trapV2, inform, allV3 });

var users = new List<User>();
<!-- User info redacted -->
var userRegistry = new UserRegistry(users.ToArray());

var listener = new Listener();
listener.Users = userRegistry;

// Special handler for SNMPv3 Traps
listener.MessageReceived += FrontLineMessageHandler;

var factory = new SnmpApplicationFactory(store, composed, messageFactory);

_engine = new SnmpEngine(factory, listener, new EngineGroup());

_engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, 162));
_engine.Listener.AddBinding(new IPEndPoint(IPAddress.IPv6Any, 162));
_engine.Start();

_logger.Info("Started SNMP engine");

Error signing output with public key

Hi,
I've been using your tool for quite some years, compiling the source code on my computer. Each time I must remove the signature file. I understand a commercial product need some kind of tampering protection, but does a public repository on Github needs this?

Error	CS7027	Error signing output with public key from file 'sharpsnmplib.snk' -- File not found.	SharpSnmpLib.NetStandard	E:\Visual Studio 2017\sharpsnmplib-9.0.8\SharpSnmpLib\CSC	1	Active

SnmpMessageExtension.GetReponseAsync throws ArgumentException when response is malformed with report PDU and version 2.

We're calling SnmpMessageExtension.GetReponseAsync on an ISnmpMessage with the version set to 2 and it's failing with this exception:

System.AggregateException: One or more errors occurred. ---> System.ArgumentException: only v3 is supported
Parameter name: version
at Lextm.SharpSnmpLib.Messaging.ReportMessage..ctor(VersionCode version, Header header, SecurityParameters parameters, Scope scope, IPrivacyProvider privacy, Byte[] length)
at Lextm.SharpSnmpLib.Messaging.MessageFactory.ParseMessage(Int32 first, Stream stream, UserRegistry registry)
at Lextm.SharpSnmpLib.Messaging.MessageFactory.ParseMessages(Byte[] buffer, Int32 index, Int32 length, UserRegistry registry)
at Lextm.SharpSnmpLib.Messaging.SnmpMessageExtension.d__14.MoveNext()

I suspect the cause is that the server we're communicating with (which we don't control) is returning a malformed response with the report pdu type but the version is set to 2.

It seems like in this case an SnmpException should be thrown instead of an ArgumentException when this happens since the problem is caused by the response from the remote server and not any a malformed argument provided by our code.

truncation error for 32-bit integer coding

I keep getting the following error 80% of the time while calling: Messenger.Get

Lextm.SharpSnmpLib.SnmpException: data construction exception ---> System.ArgumentException: truncation error for 32-bit integer coding
Parameter name: length
at Lextm.SharpSnmpLib.Integer32..ctor(Tuple2 length, Stream stream) at Lextm.SharpSnmpLib.DataFactory.CreateSnmpData(Int32 type, Stream stream) --- End of inner exception stack trace --- at Lextm.SharpSnmpLib.DataFactory.CreateSnmpData(Int32 type, Stream stream) at Lextm.SharpSnmpLib.ResponsePdu..ctor(Tuple2 length, Stream stream)
at Lextm.SharpSnmpLib.DataFactory.CreateSnmpData(Int32 type, Stream stream)
at Lextm.SharpSnmpLib.Sequence..ctor(Tuple2 length, Stream stream) at Lextm.SharpSnmpLib.DataFactory.CreateSnmpData(Int32 type, Stream stream) at Lextm.SharpSnmpLib.Messaging.MessageFactory.ParseMessage(Int32 first, Stream stream, UserRegistry registry) at Lextm.SharpSnmpLib.Messaging.MessageFactory.ParseMessages(Byte[] buffer, Int32 index, Int32 length, UserRegistry registry) at Lextm.SharpSnmpLib.Messaging.SnmpMessageExtension.GetResponse(ISnmpMessage request, Int32 timeout, IPEndPoint receiver, UserRegistry registry, Socket udpSocket) at Lextm.SharpSnmpLib.Messaging.SnmpMessageExtension.GetResponse(ISnmpMessage request, Int32 timeout, IPEndPoint receiver, Socket udpSocket) at Lextm.SharpSnmpLib.Messaging.SnmpMessageExtension.GetResponse(ISnmpMessage request, Int32 timeout, IPEndPoint receiver) at Lextm.SharpSnmpLib.Messaging.Messenger.Get(VersionCode version, IPEndPoint endpoint, OctetString community, IList1 variables, Int32 timeout)
at EnvConf.Program.d__1.MoveNext() in ...\Program.cs:line 48

const string endpointInput = "192.168.1.1";
            const string communityInput = "public";

            if (!IPAddress.TryParse(endpointInput, out IPAddress ip))
            {
                foreach ( var address in (await Dns.GetHostAddressesAsync(endpointInput))
                        .Where(address => address.AddressFamily == AddressFamily.InterNetwork))
                {
                    ip = address;
                    break;
                }
                if (ip == null)
                {
                    Console.WriteLine("IP Address was not valid.");
                    return;
                }
            }

            try
            {
                var vList = new List<Variable>()
                {
                    new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.5.0")),
                    new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0"))
                };

                var endpoint = new IPEndPoint(ip, 161);
                foreach (var variable in Messenger.Get(VersionCode.V2, endpoint, new OctetString(communityInput), vList, 1000))
                {
                    Console.WriteLine($"{variable.Id}: {variable.Data}");
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }

I'm using Visual Studio 2017 RTM with .Net Core.


Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

DiscoverAsync returns 0.0.0.0 IP address

As described in the title, when I use DiscoverAsync, in the AgentFound event the e.Agent property return 0.0.0.0 instead of the proper ip address.

Discover works fine.
Using latest 9.2 version.
Thanks!

Error NoSuchName {"error in response"}

I trying the library and am using the sample code. I can use snmpwalk and it works fine :
snmpwalk -v 1 -c public localhost .1.3.6.1.2.1.1.4

Output :
SNMPv2-MIB::sysContact.0 = STRING: Administrator [email protected] End of MIB

I also used ManageEngine MIBBrowser and it works fine, but using the library i keep getting the error {"error in response"} and when i check the detail of the error, the ErrorStatus is NoSuchName.

Here is my code

var result = Messenger.Get(VersionCode.V1,
                           new IPEndPoint(IPAddress.Parse("192.168.0.101"), 161),
                           new OctetString("public"),
                           new List<Variable> { new Variable(new ObjectIdentifier(ObjectIdentifier.Convert(".1.3.6.1.2.1.1.4"))) },
                           60000);

What am i doing wrong?

Allow for Timeout in Async functions

The async functions (particularly GetAsync, SetAsync, and BulkWalkAsync) do not have a timeout like the non-async ones did. It would be extremely helpful to have these built in rather than waiting for an error (which depending on the network can take a long time)

How to set a timeout on snmp requests

How can I set a timeout on snmp requests like SnmpGetAsync or SnmpWalkAsync in order not to wait indefinitely for result? I would like to get an exception for instance when remote host in unavailable for some period of time.

DESPrivacyProvider is not working with .net Core

Hi,

currently I try to use the DESPrivacyProvider to get some bulk data from a Netgear Switch by I always get the following exception:

System.PlatformNotSupportedException: Operation is not supported on this platform.
at Lextm.SharpSnmpLib.Security.DESPrivacyProvider.Encrypt(Byte[] unencryptedData, Byte[] key, Byte[] privacyParameters)
at Lextm.SharpSnmpLib.Security.DESPrivacyProvider.Encrypt(ISnmpData data, SecurityParameters parameters)
at Lextm.SharpSnmpLib.Security.PrivacyProviderExtension.ComputeHash(IPrivacyProvider privacy, VersionCode version, Header header, SecurityParameters parameters, ISegment scope)
at Lextm.SharpSnmpLib.Messaging.GetBulkRequestMessage..ctor(VersionCode version, Int32 messageId, Int32 requestId, OctetString userName, Int32 nonRepeaters, Int32 maxRepetitions, IList`1 variables, IPrivacyProvider privacy, Int32 maxMessageSize, ISnmpMessage report)
at Netgear.Client.NetgearClient.GetStatistics(String host, String username, String password, String encryptionKey) in C:\Users\R2D2\Documents\admin.wenz.io\Netgear.Client\NetgearClient.cs:line 23
at admin.wenz.io.Web.Tasks.GetStatistics(PerformContext context) in

I guess this is by design because of line 103-105: https://github.com/lextm/sharpsnmplib/blob/master/SharpSnmpLib/Security/DESPrivacyProvider.cs

This is my code for connection:

            Discovery discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
            ReportMessage report = discovery.GetResponse(60000, new IPEndPoint(IPAddress.Parse(host), 161));
            var auth = new SHA1AuthenticationProvider(new OctetString(password));
            var priv = new DESPrivacyProvider(new OctetString(encryptionKey), auth);

            GetBulkRequestMessage request = new GetBulkRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, new OctetString(username), 0, int.MaxValue, new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.2.2.1.16")) }, priv, Messenger.MaxMessageSize, report);
            ISnmpMessage reply = request.GetResponse(60000, new IPEndPoint(IPAddress.Parse(host), 161));


            var result = reply.Pdu().Variables;

Is there some work around to still connect to my switch with ASP.net core 2?

Thanks,
Steffen

The SocketAwaitable class seems to be leaking resources.

The SocketAwaitable class seems to be leaking resources in #SNMP v 9.0.3.
I think it is probably caused by strong reference.

public SocketAwaitable(SocketAsyncEventArgs eventArgs)
{
    if (eventArgs == null)
    {
        throw new ArgumentNullException(nameof(eventArgs));
    }

    this.m_eventArgs = eventArgs;
    eventArgs.Completed += delegate   // <----- strong reference?
    {
        var prev = m_continuation ?? Interlocked.CompareExchange(
            ref m_continuation, SENTINEL, null);
        if (prev != null) prev();
    };
}

It might be better to do the following:

public SocketAwaitable(SocketAsyncEventArgs eventArgs)
{
    if (eventArgs == null)
    {
        throw new ArgumentNullException(nameof(eventArgs));
    }

    this.m_eventArgs = eventArgs;

    // Instead of anonymous method, change to private method...
    eventArgs.Completed += this.eventArgs_Completed;
}
private void eventArgs_Completed(object sender, SocketAsyncEventArgs e)
{
    var prev = m_continuation ?? Interlocked.CompareExchange(
        ref m_continuation, SENTINEL, null);
    if (prev != null) prev();
}
internal void Reset()
{
    // Release event handler at reset...
    this.m_eventArgs.Completed -= this.eventArgs_Completed;
    this.m_wasCompleted = false;
    this.m_continuation = null;
}

How is it?


Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

snmpEngineBoots bug in EngineGroup.cs, IsInTime()

according to RFC 2574 page 27:

the local value of snmpEngineBoots is 2147483647

        // as local value of snmpEngineBoots is currentTimeData[0] but not currentTimeData[1], 
        // then there is an error here.
        // so, we should replace this wrong line:
        // if (currentTimeData[1] == int.MaxValue)
        // with the new one:
        if (currentTimeData[0] == int.MaxValue)

OctetString Field (with Hex values) delivers false values!

I am getting a field from an HP server (.1.3.6.1.4.1.232.11.2.10.7.0). This field contains status infos as a octect string (hex values).

Sadly the delivered values does not match and are faulty.

For example with another MIB Browser (ireasoning) i get the correct values:

0x02 04 02 02 02 02 02 02 02 02 01 01 01 02 04 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

If i use the sharp snmp lib the values are completly different (no matter what way i try to receive them via toHexString or get the byte array and convert it myself.)

It is totally weird as there are other OIDs from HP with the same format and are working.

I am using 9.1.401.1 of your lib (due to 4.5 restrictions in my project).

Any ideas how i can debug this or provide infos on this issue to help resolve it? Thank you

Why can't I instanciate: new ObjectIdentifier("1")

Hi!

When I do this
new ObjectIdentifier("1")

(i.e. parsing the OID value string "1" which is what the "iso" node of the SNMPv2-SMI MIB refers to), I get an ArgumentException saying "The length of the shortest identifier is two".

Why? I think the OID "1" (and also "0") should be perfectly legal.

Thanks
Karlo

SNMPv3 BulkWalk fails with DecryptionException

Hello!

I can successfully do Get and Set using SNMPv2 and v3 against a simple agent realized using the Lextm.SharpSnmpLib.Pipeline.SnmpEngine class.

Also, by calling Messenger.BulkWalk I can successfully walk the MIB using SNMPv2. But the same fails for SNMPv3. As far as I can see, a DecryptionException is thrown by the line "scope = new Scope((Sequence)privacy.Decrypt(body[3], parameters));" inside the MessageFactory.ParseMessage method on the agent side. I assume it is the GetBulkRequest message that can't be deserialized here. I add my internal logging from the agent side below, fwiw.

Do you have a unit test for doing a BulkWalk over SNMPv3 ? Can you repro this problem?

Thanks
Karlo


--- This works just fine with SNMPv2

REQ (SecurityLevel=0, UserName=public):
PDU Type GetBulkRequest Id 1609110994 NonRepeaters/MaxRepetitions (0/25) Varbinds 1
sysObjectID.0 (Null) Null
RESP:
PDU Type Response Id 1609110994 Error (NoError/0) Varbinds 5
sysUpTime.0 (TimeTicks) 00:00:00
sysContact.0 (OctetString) 42
sysName.0 (OctetString) My-sysName-value
snmpEnableAuthenTraps.0 (Integer32) enabled(1)
snmpEnableAuthenTraps.0 (EndOfMibView) EndOfMibView

--- The same fails using SNMPv3

REQ (SecurityLevel=0):
PDU Type Unknown(SNMPv3) Id 0 Varbinds 0
RESP:
PDU Type Report(SNMPv3) Id 0 Error (NoError/0) Varbinds 1
usmStatsDecryptionErrors.0 (Counter32) 0

The name 'TypeResolver' does not exist

I get this when compiling the "Classic" solution:

Error CS0103 The name 'TypeResolver' does not exist in the current context SharpSnmpLib.Full E:\Visual Studio 2017\sharpsnmplib-9.0.8\SharpSnmpLib\Pipeline\HandlerMapping.cs 114 Active

        private static IMessageHandler CreateMessageHandler(string assemblyName, string type)
        {
            foreach (var assembly in from assembly in TypeResolver.GetAssemblies()
                                          let name = assembly.GetName().Name
                                          where string.Compare(name, assemblyName, StringComparison.OrdinalIgnoreCase) == 0
                                          select assembly)
            {
                return (IMessageHandler)Activator.CreateInstance(assembly.GetType(type));
            }
#if NETSTANDARD
            return (IMessageHandler)Activator.CreateInstance(TypeResolver.Load(assemblyName, type));
#else
            return (IMessageHandler)Activator.CreateInstance(AppDomain.CurrentDomain.Load(assemblyName).GetType(type));
#endif
        }

DiscoverAsync strange behaviour between Debug sessions

I am experiencing a strange behaviour in Visual Studio 2015.
If I use the DiscoveryAsync method, as presented in the samples (+ .ConfigureAwait(false) to avoid deadlocks), I get many devices, the program obeys the interval settings - so it works well.
Then if I press stop, and then start again the Debugging session, from console output results I can see that only a few devices are found, and the method does not obey the interval setting.

I tested this behaviour with the non async version of the method, and this is not present there.

Could it be the case that I am doing something wrong, or can I use the Async version in a production code reliably?

Thanks in advance! ๐Ÿ‘


Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

Add ToIPAddress in Helper class

@lextm, Can you add an extension to convert OctetString to IPAddress in the helper class?

Something like this:

public static IPAddress ToIPAddress(this OctetString address)
        {
            var raw = address.GetRaw();
            if (raw.Length != 4)
            {
                throw new InvalidCastException(string.Format(CultureInfo.InvariantCulture, "the data length is not equal to 4: {0}", raw.Length));
            }

            return new IPAddress(raw);
        }

Bulkwalk return different data than simple get

If I use Bulkwalk, to get MAC address data from a Samsung ML-3470, I get 00-01-00-00-00 MAC address as answer.
If I use a simple get command to get the exact oid, I get the proper MAC address.

Thanks for the help with these.

This is the Bulkwalk:
List<Variable> res = new List<Variable>(); Messenger.BulkWalk(VersionCode.V2, e.Agent, new OctetString(Properties.App.Default.community), new ObjectIdentifier("1.3.6.1.2.1.2.2.1.6"), res, 14000, 4, WalkMode.WithinSubtree, null, null);
Returns this 00-01 MAC address on OID 1.3.6.1.2.1.2.2.1.6.1 and 1.3.6.1.2.1.2.2.1.6.6.

This Get command:
IList<Variable> res = Messenger.Get( v, e.Agent, new OctetString(Properties.App.Default.community), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.2.2.1.6.1")) }, 7000);

This gets the proper MAC address.

Other devices have no issues.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.