├── .gitignore
├── AgentParameters.cs
├── AsnType.cs
├── AsyncRequestResult.cs
├── AsyncRequestState.cs
├── CHANGES.txt
├── COPYING
├── CTarget.cs
├── Exception
├── SnmpAuthenticationException.cs
├── SnmpDecodingException.cs
├── SnmpErrorStatusException.cs
├── SnmpException.cs
├── SnmpInvalidPduTypeException.cs
├── SnmpInvalidVersionException.cs
├── SnmpNetworkException.cs
└── SnmpPrivacyException.cs
├── IAgentParameters.cs
├── ITarget.cs
├── MutableByte.cs
├── Pdu.cs
├── PduErrorStatus.cs
├── PduType.cs
├── Properties
└── AssemblyInfo.cs
├── README.md
├── SMIDataType.cs
├── SMIDataTypeCode.cs
├── SecureAgentParameters.cs
├── SimpleSnmp.cs
├── Snmp.cs
├── SnmpConstants.cs
├── SnmpError.cs
├── SnmpPacket.cs
├── SnmpSharpNet.csproj
├── SnmpSharpNet.sln
├── SnmpV1Packet.cs
├── SnmpV1PduErrorStatus.cs
├── SnmpV1TrapGenericErrorCode.cs
├── SnmpV1TrapPacket.cs
├── SnmpV2Packet.cs
├── SnmpV2PduErrorStatus.cs
├── SnmpV3Packet.cs
├── SnmpVariableType.cs
├── SnmpVersion.cs
├── TrapAgent.cs
├── TrapPdu.cs
├── Types
├── Counter32.cs
├── Counter64.cs
├── EndOfMibView.cs
├── EthernetAddress.cs
├── Gauge32.cs
├── Integer32.cs
├── IpAddress.cs
├── NoSuchInstance.cs
├── NoSuchObject.cs
├── Null.cs
├── OctetString.cs
├── Oid.cs
├── Opaque.cs
├── Sequence.cs
├── TimeTicks.cs
├── UInteger32.cs
├── V2Error.cs
└── V2PartyClock.cs
├── UTarget.cs
├── UdpTarget.cs
├── UdpTransport.cs
├── Vb.cs
├── VbCollection.cs
├── gpl-3_0.txt
├── keypair.snk
├── lgpl.txt
├── public.snk
└── security
├── Authentication.cs
├── AuthenticationDigests.cs
├── AuthenticationMD5.cs
├── AuthenticationSHA1.cs
├── AuthenticationSHA256.cs
├── AuthenticationSHA384.cs
├── AuthenticationSHA512.cs
├── IAuthenticationDigest.cs
├── IPrivacyProtocol.cs
├── MsgFlags.cs
├── Privacy3DES.cs
├── PrivacyAES.cs
├── PrivacyAES128.cs
├── PrivacyAES192.cs
├── PrivacyAES256.cs
├── PrivacyDES.cs
├── PrivacyProtocol.cs
├── PrivacyProtocols.cs
├── SNMPV3ReportError.cs
├── ScopedPdu.cs
└── UserSecurityModel.cs
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | artifacts/
46 |
47 | *_i.c
48 | *_p.c
49 | *_i.h
50 | *.ilk
51 | *.meta
52 | *.obj
53 | *.pch
54 | *.pdb
55 | *.pgc
56 | *.pgd
57 | *.rsp
58 | *.sbr
59 | *.tlb
60 | *.tli
61 | *.tlh
62 | *.tmp
63 | *.tmp_proj
64 | *.log
65 | *.vspscc
66 | *.vssscc
67 | .builds
68 | *.pidb
69 | *.svclog
70 | *.scc
71 |
72 | # Chutzpah Test files
73 | _Chutzpah*
74 |
75 | # Visual C++ cache files
76 | ipch/
77 | *.aps
78 | *.ncb
79 | *.opendb
80 | *.opensdf
81 | *.sdf
82 | *.cachefile
83 | *.VC.db
84 | *.VC.VC.opendb
85 |
86 | # Visual Studio profiler
87 | *.psess
88 | *.vsp
89 | *.vspx
90 | *.sap
91 |
92 | # TFS 2012 Local Workspace
93 | $tf/
94 |
95 | # Guidance Automation Toolkit
96 | *.gpState
97 |
98 | # ReSharper is a .NET coding add-in
99 | _ReSharper*/
100 | *.[Rr]e[Ss]harper
101 | *.DotSettings.user
102 |
103 | # JustCode is a .NET coding add-in
104 | .JustCode
105 |
106 | # TeamCity is a build add-in
107 | _TeamCity*
108 |
109 | # DotCover is a Code Coverage Tool
110 | *.dotCover
111 |
112 | # NCrunch
113 | _NCrunch_*
114 | .*crunch*.local.xml
115 | nCrunchTemp_*
116 |
117 | # MightyMoose
118 | *.mm.*
119 | AutoTest.Net/
120 |
121 | # Web workbench (sass)
122 | .sass-cache/
123 |
124 | # Installshield output folder
125 | [Ee]xpress/
126 |
127 | # DocProject is a documentation generator add-in
128 | DocProject/buildhelp/
129 | DocProject/Help/*.HxT
130 | DocProject/Help/*.HxC
131 | DocProject/Help/*.hhc
132 | DocProject/Help/*.hhk
133 | DocProject/Help/*.hhp
134 | DocProject/Help/Html2
135 | DocProject/Help/html
136 |
137 | # Click-Once directory
138 | publish/
139 |
140 | # Publish Web Output
141 | *.[Pp]ublish.xml
142 | *.azurePubxml
143 | # TODO: Comment the next line if you want to checkin your web deploy settings
144 | # but database connection strings (with potential passwords) will be unencrypted
145 | *.pubxml
146 | *.publishproj
147 |
148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
149 | # checkin your Azure Web App publish settings, but sensitive information contained
150 | # in these scripts will be unencrypted
151 | PublishScripts/
152 |
153 | # NuGet Packages
154 | *.nupkg
155 | # The packages folder can be ignored because of Package Restore
156 | **/packages/*
157 | # except build/, which is used as an MSBuild target.
158 | !**/packages/build/
159 | # Uncomment if necessary however generally it will be regenerated when needed
160 | #!**/packages/repositories.config
161 | # NuGet v3's project.json files produces more ignoreable files
162 | *.nuget.props
163 | *.nuget.targets
164 |
165 | # Microsoft Azure Build Output
166 | csx/
167 | *.build.csdef
168 |
169 | # Microsoft Azure Emulator
170 | ecf/
171 | rcf/
172 |
173 | # Windows Store app package directories and files
174 | AppPackages/
175 | BundleArtifacts/
176 | Package.StoreAssociation.xml
177 | _pkginfo.txt
178 |
179 | # Visual Studio cache files
180 | # files ending in .cache can be ignored
181 | *.[Cc]ache
182 | # but keep track of directories ending in .cache
183 | !*.[Cc]ache/
184 |
185 | # Others
186 | ClientBin/
187 | ~$*
188 | *~
189 | *.dbmdl
190 | *.dbproj.schemaview
191 | *.pfx
192 | *.publishsettings
193 | node_modules/
194 | orleans.codegen.cs
195 |
196 | # Since there are multiple workflows, uncomment next line to ignore bower_components
197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
198 | #bower_components/
199 |
200 | # RIA/Silverlight projects
201 | Generated_Code/
202 |
203 | # Backup & report files from converting an old project file
204 | # to a newer Visual Studio version. Backup files are not needed,
205 | # because we have git ;-)
206 | _UpgradeReport_Files/
207 | Backup*/
208 | UpgradeLog*.XML
209 | UpgradeLog*.htm
210 |
211 | # SQL Server files
212 | *.mdf
213 | *.ldf
214 |
215 | # Business Intelligence projects
216 | *.rdl.data
217 | *.bim.layout
218 | *.bim_*.settings
219 |
220 | # Microsoft Fakes
221 | FakesAssemblies/
222 |
223 | # GhostDoc plugin setting file
224 | *.GhostDoc.xml
225 |
226 | # Node.js Tools for Visual Studio
227 | .ntvs_analysis.dat
228 |
229 | # Visual Studio 6 build log
230 | *.plg
231 |
232 | # Visual Studio 6 workspace options file
233 | *.opt
234 |
235 | # Visual Studio LightSwitch build output
236 | **/*.HTMLClient/GeneratedArtifacts
237 | **/*.DesktopClient/GeneratedArtifacts
238 | **/*.DesktopClient/ModelManifest.xml
239 | **/*.Server/GeneratedArtifacts
240 | **/*.Server/ModelManifest.xml
241 | _Pvt_Extensions
242 |
243 | # Paket dependency manager
244 | .paket/paket.exe
245 | paket-files/
246 |
247 | # FAKE - F# Make
248 | .fake/
249 |
250 | # JetBrains Rider
251 | .idea/
252 | *.sln.iml
253 |
--------------------------------------------------------------------------------
/AgentParameters.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | using System.Collections.Generic;
18 | using System.Text;
19 | using System.Net;
20 |
21 | namespace SnmpSharpNet
22 | {
23 | ///
24 | /// SNMP Agent specific values.
25 | ///
26 | ///
27 | /// This class stores values to access SNMP version 1 and version 2
28 | /// agents.
29 | ///
30 | /// Pass this class with your request data (Pdu) to the request method of the target class to make
31 | /// a request.
32 | ///
33 | public class AgentParameters: IAgentParameters
34 | {
35 | ///
36 | /// Agent protocol version
37 | ///
38 | protected Integer32 _version;
39 | ///
40 | /// SNMP community name for SNMP v1 and v2 protocol versions
41 | ///
42 | protected OctetString _community;
43 | ///
44 | /// Flag that disables checking of host IP address and port number from which reply is received. If not disabled, only
45 | /// replies from the host IP/port to which request was sent will be considered valid and all others will be ignored.
46 | ///
47 | /// Default value is: false (reply source check is enabled)
48 | ///
49 | /// Set to true if you wish to disable this check.
50 | ///
51 | protected bool _disableReplySourceCheck;
52 | ///
53 | /// Standard constructor
54 | ///
55 | public AgentParameters()
56 | {
57 | _version = new Integer32((int)SnmpVersion.Ver1);
58 | _community = new OctetString("public");
59 | _disableReplySourceCheck = false;
60 | }
61 | ///
62 | /// Copy constructor. Initialize the class with the values of the parameter class values.
63 | ///
64 | /// Parameter class.
65 | public AgentParameters(AgentParameters second)
66 | {
67 | _version.Value = (int)second.Version;
68 | _community.Set(second.Community);
69 | _disableReplySourceCheck = second.DisableReplySourceCheck;
70 | }
71 | ///
72 | /// Constructor
73 | ///
74 | /// SNMP protocol version. Acceptable values are SnmpConstants.SNMPV1 and
75 | /// SnmpConstants.SNMPV2
76 | public AgentParameters(SnmpVersion version)
77 | : this()
78 | {
79 | _version.Value = (int)version;
80 | }
81 | ///
82 | /// Constructor
83 | ///
84 | /// Agent SNMP community name
85 | public AgentParameters(OctetString community)
86 | : this()
87 | {
88 | _community.Set(community);
89 | }
90 | ///
91 | /// Constructor
92 | ///
93 | /// SNMP Protocol version
94 | /// SNMP community name
95 | public AgentParameters(SnmpVersion version, OctetString community)
96 | : this(version)
97 | {
98 | _community.Set(community);
99 | }
100 | ///
101 | /// Constructor
102 | ///
103 | /// SNMP Protocol version
104 | /// SNMP community name
105 | /// Should reply source IP address/port number be checked on reply reception
106 | public AgentParameters(SnmpVersion version, OctetString community, bool disableReplySourceCheck)
107 | : this(version, community)
108 | {
109 | _disableReplySourceCheck = disableReplySourceCheck;
110 | }
111 | ///
112 | /// Get/Set SNMP protocol version.
113 | ///
114 | /// Thrown when attempting to set protocol version
115 | /// other then version 1 or 2c
116 | public virtual SnmpVersion Version
117 | {
118 | get
119 | {
120 | return (SnmpVersion)_version.Value;
121 | }
122 | set
123 | {
124 | if (value != SnmpVersion.Ver1 && value != SnmpVersion.Ver2)
125 | throw new SnmpInvalidVersionException("Valid SNMP versions are 1 or 2");
126 | _version.Value = (int)value;
127 | }
128 | }
129 | ///
130 | /// Return SNMP version Integer32 object
131 | ///
132 | /// Integer32 object
133 | public Integer32 GetVersion()
134 | {
135 | return _version;
136 | }
137 | ///
138 | /// Get SNMP version 1 or 2 community name object
139 | ///
140 | virtual public OctetString Community
141 | {
142 | get
143 | {
144 | return _community;
145 | }
146 | }
147 |
148 | ///
149 | /// Get/Set flag that disables checking of host IP address and port number from which reply is received. If not disabled, only
150 | /// replies from the host IP/port to which request was sent will be considered valid and all others will be ignored.
151 | ///
152 | public bool DisableReplySourceCheck
153 | {
154 | get
155 | {
156 | return _disableReplySourceCheck;
157 | }
158 | set
159 | {
160 | _disableReplySourceCheck = value;
161 | }
162 | }
163 |
164 | ///
165 | /// Validate object.
166 | ///
167 | /// true if object is valid, otherwise false
168 | public bool Valid()
169 | {
170 | if (_community != null && _community.Length > 0 && _version != null)
171 | {
172 | if (_version.Value == (int)SnmpVersion.Ver1 || _version.Value == (int)SnmpVersion.Ver2)
173 | return true;
174 | }
175 | return false;
176 | }
177 |
178 | ///
179 | /// Initialize SNMP packet class with agent parameters. In this class, SNMP community name is
180 | /// set in SNMPv1 and SNMPv2 packets.
181 | ///
182 | /// Packet class to initialize
183 | public void InitializePacket(SnmpPacket packet)
184 | {
185 | if (packet is SnmpV1Packet)
186 | {
187 | SnmpV1Packet pkt = (SnmpV1Packet)packet;
188 | pkt.Community.Set(_community);
189 | }
190 | else if (packet is SnmpV2Packet)
191 | {
192 | SnmpV2Packet pkt = (SnmpV2Packet)packet;
193 | pkt.Community.Set(_community);
194 | }
195 | else
196 | throw new SnmpInvalidVersionException("Invalid SNMP version.");
197 | }
198 |
199 | ///
200 | /// Clone current object
201 | ///
202 | /// Duplicate object initialized with values from this class.
203 | public object Clone()
204 | {
205 | return new AgentParameters(this.Version,this.Community, this.DisableReplySourceCheck);
206 | }
207 | }
208 | }
209 |
--------------------------------------------------------------------------------
/AsyncRequestResult.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace SnmpSharpNet
6 | {
7 | ///
8 | /// Result codes sent by UdpTarget class to the SnmpAsyncCallback delegate.
9 | ///
10 | public enum AsyncRequestResult
11 | {
12 | ///
13 | /// No error. Data was received from the socket.
14 | ///
15 | NoError = 0,
16 | ///
17 | /// Request is in progress. A new request can not be initiated until previous request completes.
18 | ///
19 | RequestInProgress,
20 | ///
21 | /// Request has timed out. Maximum number of retries has been reached without receiving a reply
22 | /// from the peer request was sent to
23 | ///
24 | Timeout,
25 | ///
26 | /// An error was encountered when attempting to send data to the peer. Request failed.
27 | ///
28 | SocketSendError,
29 | ///
30 | /// An error was encountered when attempting to receive data from the peer. Request failed.
31 | ///
32 | SocketReceiveError,
33 | ///
34 | /// Request has been terminated by the user.
35 | ///
36 | Terminated,
37 | ///
38 | /// No data was received from the peer
39 | ///
40 | NoDataReceived,
41 | ///
42 | /// Authentication error
43 | ///
44 | AuthenticationError,
45 | ///
46 | /// Privacy error
47 | ///
48 | PrivacyError,
49 | ///
50 | /// Error encoding SNMP packet
51 | ///
52 | EncodeError,
53 | ///
54 | /// Error decoding SNMP packet
55 | ///
56 | DecodeError
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/AsyncRequestState.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System.Net;
17 | using System.Threading;
18 |
19 | namespace SnmpSharpNet
20 | {
21 | ///
22 | /// Internal class holding relevant information for async requests.
23 | ///
24 | internal class AsyncRequestState
25 | {
26 | ///
27 | /// Peer end point
28 | ///
29 | protected IPEndPoint _endPoint;
30 | ///
31 | /// Packet
32 | ///
33 | protected byte[] _packet;
34 | ///
35 | /// Packet length
36 | ///
37 | protected int _packetLength;
38 | ///
39 | /// Maximum number of retries (0 = single request, no retries)
40 | ///
41 | protected int _maxRetries;
42 | ///
43 | /// Request timeout in milliseconds
44 | ///
45 | protected int _timeout;
46 | ///
47 | /// Timer class
48 | ///
49 | protected Timer _timer;
50 | ///
51 | /// Current retry count. Value represents the number of retries that have been sent
52 | /// excluding the original request.
53 | ///
54 | protected int _currentRetry;
55 |
56 | ///
57 | /// Get/Set end point
58 | ///
59 | public System.Net.IPEndPoint EndPoint
60 | {
61 | get { return _endPoint; }
62 | set { _endPoint = value; }
63 | }
64 | ///
65 | /// Get/Set packet buffer
66 | ///
67 | public byte[] Packet
68 | {
69 | get { return _packet; }
70 | set { _packet = value; }
71 | }
72 | ///
73 | /// Get/Set packet length value
74 | ///
75 | public int PacketLength
76 | {
77 | get { return _packetLength; }
78 | set { _packetLength = value; }
79 | }
80 | ///
81 | /// Get/Set maximum retry value
82 | ///
83 | public int MaxRetries
84 | {
85 | get { return _maxRetries; }
86 | set { _maxRetries = value; }
87 | }
88 | ///
89 | /// Get/Set timeout value
90 | ///
91 | public int Timeout
92 | {
93 | get { return _timeout; }
94 | set { _timeout = value; }
95 | }
96 | ///
97 | /// Get/Set timer class
98 | ///
99 | public System.Threading.Timer Timer
100 | {
101 | get { return _timer; }
102 | set { _timer = value; }
103 | }
104 | ///
105 | /// Get/Set current retry count
106 | ///
107 | public int CurrentRetry
108 | {
109 | get { return _currentRetry; }
110 | set { _currentRetry = value; }
111 | }
112 | ///
113 | /// Constructor.
114 | ///
115 | /// Peer IP address
116 | /// Peer UDP port number
117 | /// Maximum number of retries
118 | /// Timeout value in milliseconds
119 | public AsyncRequestState(IPAddress peerIP, int peerPort, int maxretries, int timeout)
120 | {
121 | _endPoint = new IPEndPoint(peerIP, peerPort);
122 | _maxRetries = maxretries;
123 | _timeout = timeout;
124 | // current retry value is set to -1 because we do not count the first request as a retry.
125 | _currentRetry = -1;
126 | _timer = null;
127 | }
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/CTarget.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Net;
5 |
6 | namespace SnmpSharpNet
7 | {
8 | ///
9 | /// Community based SNMP target. Used for SNMP version 1 and version 2c.
10 | ///
11 | public class CTarget: ITarget
12 | {
13 | #region Private variables
14 | ///
15 | /// Target IP address
16 | ///
17 | protected IpAddress _address;
18 | ///
19 | /// Target port number
20 | ///
21 | protected int _port;
22 | ///
23 | /// Target SNMP version number
24 | ///
25 | protected SnmpVersion _version;
26 | ///
27 | /// Target request timeout period in milliseconds
28 | ///
29 | protected int _timeout;
30 | ///
31 | /// Target maximum retry count
32 | ///
33 | protected int _retry;
34 | ///
35 | /// SNMP community name
36 | ///
37 | protected String _community;
38 |
39 | #endregion
40 |
41 | #region Constructors
42 |
43 | ///
44 | /// Constructor
45 | ///
46 | public CTarget()
47 | {
48 | _address = new IpAddress(System.Net.IPAddress.Loopback);
49 | _port = 161;
50 | _version = SnmpVersion.Ver2;
51 | _timeout = 2000;
52 | _retry = 1;
53 | _community = "public";
54 | }
55 | ///
56 | /// Constructor
57 | ///
58 | /// Target address
59 | public CTarget(IPAddress addr)
60 | : this()
61 | {
62 | _address.Set(addr);
63 | }
64 | ///
65 | /// Constructor
66 | ///
67 | /// Target address
68 | /// SNMP community name to use with the target
69 | public CTarget(IPAddress addr, String community)
70 | : this(addr)
71 | {
72 | _community = community;
73 | }
74 | ///
75 | /// Constructor
76 | ///
77 | /// Target address
78 | /// Taret UDP port number
79 | /// SNMP community name to use with the target
80 | public CTarget(IPAddress addr, int port, String community)
81 | : this(addr,community)
82 | {
83 | _port = port;
84 | }
85 |
86 | #endregion Constructors
87 |
88 | #region Properties
89 |
90 | ///
91 | /// SNMP community name for the target
92 | ///
93 | public String Community
94 | {
95 | get
96 | {
97 | return _community;
98 | }
99 | set
100 | {
101 | _community = value;
102 | }
103 | }
104 |
105 | #endregion Properties
106 |
107 | #region ITarget Members
108 |
109 | ///
110 | /// Prepare packet for transmission by filling target specific information in the packet.
111 | ///
112 | /// SNMP packet class for the required version
113 | /// True if packet values are correctly set, otherwise false.
114 | public bool PreparePacketForTransmission(SnmpPacket packet)
115 | {
116 | if (packet.Version != _version)
117 | return false;
118 | if (_version == SnmpVersion.Ver1)
119 | {
120 | SnmpV1Packet pkt = (SnmpV1Packet)packet;
121 | pkt.Community.Set(_community);
122 | return true;
123 | }
124 | else if (_version == SnmpVersion.Ver2)
125 | {
126 | SnmpV2Packet pkt = (SnmpV2Packet)packet;
127 | pkt.Community.Set(_community);
128 | return true;
129 | }
130 | return false;
131 | }
132 | ///
133 | /// Validate received reply
134 | ///
135 | /// Received SNMP packet
136 | /// True if packet is validated, otherwise false
137 | public bool ValidateReceivedPacket(SnmpPacket packet)
138 | {
139 | if (packet.Version != _version)
140 | return false;
141 | if( _version == SnmpVersion.Ver1 ) {
142 | SnmpV1Packet pkt = (SnmpV1Packet)packet;
143 | if (pkt.Community.Equals(_community))
144 | return true;
145 | }
146 | else if( _version == SnmpVersion.Ver2 )
147 | {
148 | SnmpV2Packet pkt = (SnmpV2Packet)packet;
149 | if (pkt.Community.Equals(_community))
150 | return true;
151 | }
152 | return false;
153 | }
154 | ///
155 | /// Get version of SNMP protocol this target supports
156 | ///
157 | /// Thrown when SNMP version other then 1 or 2c is set
158 | public SnmpVersion Version
159 | {
160 | get { return _version; }
161 | set
162 | {
163 | if (value != SnmpVersion.Ver1 && value != SnmpVersion.Ver2)
164 | throw new SnmpInvalidVersionException("CTarget is only suitable for use with SNMP v1 and v2c protocol versions.");
165 | _version = value;
166 | }
167 | }
168 | ///
169 | /// Timeout in milliseconds for the target. Valid timeout values are between 100 and 10000 milliseconds.
170 | ///
171 | public int Timeout
172 | {
173 | get
174 | {
175 | return _timeout;
176 | }
177 | set
178 | {
179 | if (value < 100 || value > 10000)
180 | throw new OverflowException("Valid timeout value is between 100 milliseconds and 10000 milliseconds");
181 | _timeout = value;
182 | }
183 | }
184 | ///
185 | /// Number of retries for the target. Valid values are 0-5.
186 | ///
187 | public int Retry
188 | {
189 | get
190 | {
191 | return _retry;
192 | }
193 | set
194 | {
195 | if (value < 0 || value > 5)
196 | throw new OverflowException("Valid retry value is between 0 and 5");
197 | _retry = value;
198 | }
199 | }
200 | ///
201 | /// Target IP address
202 | ///
203 | public IpAddress Address
204 | {
205 | get
206 | {
207 | return _address;
208 | }
209 | }
210 | ///
211 | /// Target port number
212 | ///
213 | public int Port
214 | {
215 | get
216 | {
217 | return _port;
218 | }
219 | set
220 | {
221 | _port = value;
222 | }
223 | }
224 | ///
225 | /// Check validity of the target information.
226 | ///
227 | /// True if valid, otherwise false.
228 | public bool Valid()
229 | {
230 | if (_community == null || _community.Length == 0)
231 | return false;
232 | if (_address == null || !_address.Valid)
233 | return false;
234 | if (_port == 0)
235 | return false;
236 | return true;
237 | }
238 | #endregion
239 | }
240 | }
241 |
--------------------------------------------------------------------------------
/Exception/SnmpAuthenticationException.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Exception of this type is thrown when SNMP version 3 packet containing authentication information
21 | /// has failed authentication check.
22 | ///
23 | public class SnmpAuthenticationException: SnmpException
24 | {
25 | ///
26 | /// Standard constructor.
27 | ///
28 | /// Error message
29 | public SnmpAuthenticationException(string msg)
30 | : base(msg)
31 | {
32 | }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/Exception/SnmpDecodingException.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Exception thrown on failure to decode BER encoded information.
21 | ///
22 | public class SnmpDecodingException : SnmpException
23 | {
24 | ///
25 | /// standard constructor
26 | ///
27 | /// exception message
28 | public SnmpDecodingException(string msg)
29 | : base(msg)
30 | {
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Exception/SnmpErrorStatusException.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 |
18 | namespace SnmpSharpNet
19 | {
20 | ///
21 | /// Exception thrown by methods when SNMP request returned a SnmpStatus error in the reply and
22 | /// SuppressExceptions flag is set to false.
23 | ///
24 | public class SnmpErrorStatusException: Exception
25 | {
26 | ///
27 | /// SNMP reply ErrorStatus value
28 | ///
29 | protected int _errorStatus;
30 | ///
31 | /// SNMP reply ErrorIndex value
32 | ///
33 | protected int _errorIndex;
34 | ///
35 | /// Constructor
36 | ///
37 | public SnmpErrorStatusException()
38 | : base()
39 | {
40 | _errorStatus = 0;
41 | _errorIndex = 0;
42 | }
43 | ///
44 | /// Constructor
45 | ///
46 | /// Exception message
47 | /// ErrorStatus value
48 | /// ErrorIndex value
49 | public SnmpErrorStatusException(string msg, int status, int index)
50 | : base(msg)
51 | {
52 | _errorStatus = status;
53 | _errorIndex = index;
54 | }
55 | ///
56 | /// Get/Set SNMP ErrorStatus value
57 | ///
58 | public int ErrorStatus
59 | {
60 | get { return _errorStatus; }
61 | set { _errorStatus = value; }
62 | }
63 | ///
64 | /// Get/Set SNMP ErrorIndex value
65 | ///
66 | public int ErrorIndex
67 | {
68 | get { return _errorIndex; }
69 | set { _errorIndex = value; }
70 | }
71 | ///
72 | /// Get exception message
73 | ///
74 | public override string Message
75 | {
76 | get
77 | {
78 | return String.Format("{0}> ErrorStatus {1} ErrorIndex {2}", base.Message, _errorStatus, _errorIndex);
79 | }
80 | }
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/Exception/SnmpException.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 |
18 | namespace SnmpSharpNet
19 | {
20 | ///
21 | /// SNMP generic exception. Thrown every time SNMP specific error is encountered.
22 | ///
23 | [Serializable]
24 | public class SnmpException : Exception
25 | {
26 | ///
27 | /// No error
28 | ///
29 | public static int None = 0;
30 | ///
31 | /// Security model specified in the packet is not supported
32 | ///
33 | public static int UnsupportedSecurityModel = 1;
34 | ///
35 | /// Privacy enabled without authentication combination in a packet is not supported.
36 | ///
37 | public static int UnsupportedNoAuthPriv = 2;
38 | ///
39 | /// Invalid length of the authentication parameter field. Expected length is 12 bytes when authentication is
40 | /// enabled. Same length is used for both MD5 and SHA-1 authentication protocols.
41 | ///
42 | public static int InvalidAuthenticationParameterLength = 3;
43 | ///
44 | /// Authentication of the received packet failed.
45 | ///
46 | public static int AuthenticationFailed = 4;
47 | ///
48 | /// Privacy protocol requested is not supported.
49 | ///
50 | public static int UnsupportedPrivacyProtocol = 5;
51 | ///
52 | /// Invalid length of the privacy parameter field. Expected length depends on the privacy protocol. This exception
53 | /// can be raised when privacy packet contents are invalidly set by agent or if wrong privacy protocol is set in the
54 | /// packet class definition.
55 | ///
56 | public static int InvalidPrivacyParameterLength = 6;
57 | ///
58 | /// Authoritative engine id is invalid.
59 | ///
60 | public static int InvalidAuthoritativeEngineId = 7;
61 | ///
62 | /// Engine boots value is invalid
63 | ///
64 | public static int InvalidEngineBoots = 8;
65 | ///
66 | /// Received packet is outside the time window acceptable. Packet failed timeliness check.
67 | ///
68 | public static int PacketOutsideTimeWindow = 9;
69 | ///
70 | /// Invalid request id in the packet.
71 | ///
72 | public static int InvalidRequestId = 10;
73 | ///
74 | /// SNMP version 3 maximum message size exceeded. Packet that was encoded will exceed maximum message
75 | /// size acceptable in this transaction.
76 | ///
77 | public static int MaximumMessageSizeExceeded = 11;
78 | ///
79 | /// UdpTarget request cannot be processed because IAgentParameters does not contain required information
80 | ///
81 | public static int InvalidIAgentParameters = 12;
82 |
83 | ///
84 | /// Reply to a request was not received within the timeout period
85 | ///
86 | public static int RequestTimedOut = 13;
87 | ///
88 | /// Null data received on request.
89 | ///
90 | public static int NoDataReceived = 14;
91 | ///
92 | /// Security name (user name) in the reply does not match the name sent in request.
93 | ///
94 | public static int InvalidSecurityName = 15;
95 | ///
96 | /// Report packet was received when Reportable flag was set to false (we notified the peer that we do
97 | /// not receive report packets).
98 | ///
99 | public static int ReportOnNoReports = 16;
100 | ///
101 | /// Oid value type returned by an earlier operation does not match the value type returned by a subsequent entry.
102 | ///
103 | public static int OidValueTypeChanged = 17;
104 | ///
105 | /// Specified Oid is invalid
106 | ///
107 | public static int InvalidOid = 18;
108 |
109 | ///
110 | /// Error code. Provides a finer grained information about why the exception happened. This can be useful to
111 | /// the process handling the error to determine how critical the error that occured is and what followup actions
112 | /// to take.
113 | ///
114 | protected int _errorCode;
115 | ///
116 | /// Get/Set error code associated with the exception
117 | ///
118 | public int ErrorCode
119 | {
120 | get { return _errorCode; }
121 | set { _errorCode = value; }
122 | }
123 |
124 | ///
125 | /// Constructor.
126 | ///
127 | public SnmpException()
128 | : base()
129 | {
130 | }
131 | ///
132 | /// Standard constructor
133 | ///
134 | /// SNMP Exception message
135 | public SnmpException(string msg)
136 | : base(msg)
137 | {
138 | }
139 | ///
140 | /// Constructor
141 | ///
142 | /// Error code associated with the exception
143 | /// Error message
144 | public SnmpException(int errorCode, string msg)
145 | : base(msg)
146 | {
147 | _errorCode = errorCode;
148 | }
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/Exception/SnmpInvalidPduTypeException.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Exception thrown when specific PDU type was expected and a different type was received.
21 | ///
22 | public class SnmpInvalidPduTypeException: SnmpException
23 | {
24 | ///
25 | /// Constructor
26 | ///
27 | /// Error message
28 | public SnmpInvalidPduTypeException(string msg)
29 | : base(msg)
30 | {
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Exception/SnmpInvalidVersionException.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Exception thrown when invalid SNMP version was encountered in the packet
21 | ///
22 | public class SnmpInvalidVersionException: SnmpException
23 | {
24 | ///
25 | /// Standard constructor
26 | ///
27 | /// Exception error message
28 | public SnmpInvalidVersionException(string msg)
29 | : base(msg)
30 | {
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/Exception/SnmpNetworkException.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | using System;
18 |
19 | namespace SnmpSharpNet
20 | {
21 | /// SNMP network exception
22 | ///
23 | /// Exception thrown when network error was encountered. Network errors include host, network unreachable, connection refused, etc.
24 | ///
25 | /// One network exception that is not covered by this exception is request timeout.
26 | ///
27 | public class SnmpNetworkException: SnmpException
28 | {
29 | private Exception _systemException;
30 | ///
31 | /// Return system exception that caused raising of this Exception error.
32 | ///
33 | public System.Exception SystemException
34 | {
35 | get { return _systemException; }
36 | }
37 | ///
38 | /// Standard constructor
39 | ///
40 | /// System exception that caused the error
41 | /// Error message
42 | public SnmpNetworkException(Exception sysException, string msg)
43 | : base(msg)
44 | {
45 | _systemException = sysException;
46 | }
47 | ///
48 | /// Constructor. Used when system exception did not cause the error and there is no parent
49 | /// exception associated with the error.
50 | ///
51 | /// Error message
52 | public SnmpNetworkException(string msg)
53 | : base(msg)
54 | {
55 | _systemException = null;
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/Exception/SnmpPrivacyException.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 |
18 | namespace SnmpSharpNet
19 | {
20 | ///
21 | /// Privacy encryption or decryption exception
22 | ///
23 | ///
24 | /// Exception thrown when errors were encountered related to the privacy protocol encryption and decryption operations.
25 | ///
26 | /// Use ParentException field to get the causing error details.
27 | ///
28 | public class SnmpPrivacyException : SnmpException
29 | {
30 | ///
31 | /// Exception that caused this exception to be thrown
32 | ///
33 | private Exception _parentException;
34 | ///
35 | /// Exception that caused this exception to be thrown
36 | ///
37 | public Exception ParentException
38 | {
39 | get { return _parentException; }
40 | }
41 | ///
42 | /// Standard constructor initializes the exceptione error message
43 | ///
44 | /// Error message
45 | public SnmpPrivacyException(string msg)
46 | : base(msg)
47 | {
48 | }
49 |
50 | ///
51 | /// Constructor initializes error message and parent exception
52 | ///
53 | /// Parent exception
54 | /// Error message
55 | public SnmpPrivacyException(Exception ex, string msg)
56 | : base(msg)
57 | {
58 | _parentException = ex;
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/IAgentParameters.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Every agent parameters class implements this interface
21 | ///
22 | public interface IAgentParameters
23 | {
24 | ///
25 | /// Get SNMP version number.
26 | ///
27 | SnmpVersion Version
28 | {
29 | get;
30 | }
31 |
32 | ///
33 | /// Check validity of the agent properties object.
34 | ///
35 | /// true if object has all the information needed, otherwise false.
36 | bool Valid();
37 |
38 | ///
39 | /// Initialize SNMP packet class with values contained in this class.
40 | ///
41 | /// SNMP packet class
42 | void InitializePacket(SnmpPacket packet);
43 |
44 | ///
45 | /// Duplicate object
46 | ///
47 | /// Cloned copy of the object
48 | object Clone();
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/ITarget.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace SnmpSharpNet
6 | {
7 | ///
8 | /// SNMP target interface
9 | ///
10 | public interface ITarget
11 | {
12 | ///
13 | /// Prepare packet for transmission by filling target specific information in the packet.
14 | ///
15 | /// SNMP packet class for the required version
16 | /// True if packet values are correctly set, otherwise false.
17 | bool PreparePacketForTransmission(SnmpPacket packet);
18 | ///
19 | /// Validate received reply
20 | ///
21 | /// Received SNMP packet
22 | /// True if packet is validated, otherwise false
23 | bool ValidateReceivedPacket(SnmpPacket packet);
24 | ///
25 | /// Get version of SNMP protocol this target supports
26 | ///
27 | SnmpVersion Version
28 | {
29 | get;
30 | set;
31 | }
32 | ///
33 | /// Timeout in milliseconds for the target
34 | ///
35 | int Timeout
36 | {
37 | get;
38 | set;
39 | }
40 | ///
41 | /// Number of retries for the target
42 | ///
43 | int Retry
44 | {
45 | get;
46 | set;
47 | }
48 | ///
49 | /// Target IP address
50 | ///
51 | IpAddress Address
52 | {
53 | get;
54 | }
55 | ///
56 | /// Target port number
57 | ///
58 | int Port
59 | {
60 | get;
61 | set;
62 | }
63 | ///
64 | /// Check validity of the target information.
65 | ///
66 | /// True if valid, otherwise false.
67 | bool Valid();
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/PduErrorStatus.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Pdu and ScopedPdu error status value enumeration
21 | ///
22 | /// Thanks to Pavel_Tatarinov@selinc.com
23 | public enum PduErrorStatus
24 | {
25 | ///
26 | /// No error
27 | ///
28 | noError = 0,
29 | ///
30 | /// request or reply is too big
31 | ///
32 | tooBig = 1,
33 | ///
34 | /// requested name doesn't exist
35 | ///
36 | noSuchName = 2,
37 | ///
38 | /// bad value supplied
39 | ///
40 | badValue = 3,
41 | ///
42 | /// Oid is read only
43 | ///
44 | readOnly = 4,
45 | ///
46 | /// general error
47 | ///
48 | genErr = 5,
49 | ///
50 | /// access denied
51 | ///
52 | noAccess = 6,
53 | ///
54 | /// wrong type
55 | ///
56 | wrongType = 7,
57 | ///
58 | /// wrong length
59 | ///
60 | wrongLength = 8,
61 | ///
62 | /// wrong encoding
63 | ///
64 | wrongEncoding = 9,
65 | ///
66 | /// wrong value
67 | ///
68 | wrongValue = 10,
69 | ///
70 | /// no creation
71 | ///
72 | noCreation = 11,
73 | ///
74 | /// inconsistent value
75 | ///
76 | inconsistentValue = 12,
77 | ///
78 | /// resource is not available
79 | ///
80 | resourceUnavailable = 13,
81 | ///
82 | /// commit failed
83 | ///
84 | commitFailed = 14,
85 | ///
86 | /// undo failed
87 | ///
88 | undoFailed = 15,
89 | ///
90 | /// authorization error
91 | ///
92 | authorizationError = 16,
93 | ///
94 | /// not writable
95 | ///
96 | notWritable = 17,
97 | ///
98 | /// inconsistent name
99 | ///
100 | inconsistentName = 18
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/PduType.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Enumeration of available Protocol Data Unit types
21 | ///
22 | public enum PduType: byte
23 | {
24 | ///
25 | /// SNMP Get request PDU type
26 | ///
27 | Get = 0xa0,
28 | ///
29 | /// SNMP GetNext request PDU type
30 | ///
31 | GetNext = 0xa1,
32 | ///
33 | /// SNMP Response PDU type
34 | ///
35 | Response = 0xa2,
36 | ///
37 | /// SNMP Set request PDU type
38 | ///
39 | Set = 0xa3,
40 | ///
41 | /// SNMP Trap notification PDU type
42 | ///
43 | Trap = 0xa4,
44 | ///
45 | /// SNMP GetBulk request PDU type
46 | ///
47 | GetBulk = 0xa5,
48 | ///
49 | /// SNMP Inform notification PDU type
50 | ///
51 | Inform = 0xa6,
52 | ///
53 | /// SNMP version 2 Trap notification PDU type
54 | ///
55 | V2Trap = 0xa7,
56 | ///
57 | /// SNMP version 3 Report notification PDU type
58 | ///
59 | Report = 0xa8
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | [assembly: AssemblyTitle("SnmpSharpNet")]
6 | [assembly: AssemblyDescription("dotNet Simple Network Management Protocol Implementation")]
7 | [assembly: AssemblyConfiguration("")]
8 | [assembly: AssemblyCompany("Milan Sinadinovic")]
9 | [assembly: AssemblyProduct("SnmpSharpNet")]
10 | [assembly: AssemblyCopyright("Copyright © Milan Sinadinovic 2008 - 2014")]
11 | [assembly: AssemblyTrademark("")]
12 | [assembly: AssemblyCulture("")]
13 |
14 | [assembly: ComVisible(false)]
15 |
16 | [assembly: Guid("33f5795a-9f55-4965-89bc-0f413452bd0f")]
17 |
18 | [assembly: AssemblyVersion("0.9.7")]
19 | [assembly: AssemblyFileVersion("0.9.7")]
20 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # SnmpSharpNet
4 | Simple Network Management Protocol (SNMP) .Net library written in C# (csharp). Implements protocol version 1, 2 and 3.
5 | This library migrate from https://sourceforge.net/projects/snmpsharpnet/
6 |
7 | # Document
8 | [see wiki](https://github.com/rqx110/SnmpSharpNet/wiki)
9 |
--------------------------------------------------------------------------------
/SMIDataType.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 |
18 | namespace SnmpSharpNet
19 | {
20 | ///
21 | /// Collection of static helper methods making operations with SMI data types simpler and easier.
22 | ///
23 | public sealed class SMIDataType
24 | {
25 |
26 | private SMIDataType ()
27 | {
28 | }
29 | ///
30 | /// Get class instance for the SMI value type with the specific TLV encoding type code.
31 | ///
32 | /// SMI type code
33 | /// Correct SMI type class instance for the data type or null if type is not recognized
34 | public static AsnType GetSyntaxObject (byte asnType)
35 | {
36 | if (!SMIDataType.IsValidType (asnType))
37 | return null;
38 | return SMIDataType.GetSyntaxObject ((SMIDataTypeCode)asnType);
39 | }
40 | /// Used to create correct variable type object for the specified encoded type
41 | /// ASN.1 type code
42 | /// A new object matching type supplied or null if type was not recognized.
43 | public static AsnType GetSyntaxObject (SMIDataTypeCode asnType)
44 | {
45 | AsnType obj = null;
46 | if (asnType == SMIDataTypeCode.Integer)
47 | obj = new Integer32 ();
48 | else if (asnType == SMIDataTypeCode.Counter32)
49 | obj = new Counter32 ();
50 | else if (asnType == SMIDataTypeCode.Gauge32)
51 | obj = new Gauge32 ();
52 | else if (asnType == SMIDataTypeCode.Counter64)
53 | obj = new Counter64 ();
54 | else if (asnType == SMIDataTypeCode.TimeTicks)
55 | obj = new TimeTicks ();
56 | else if (asnType == SMIDataTypeCode.OctetString)
57 | obj = new OctetString ();
58 | else if (asnType == SMIDataTypeCode.Opaque)
59 | obj = new Opaque ();
60 | else if (asnType == SMIDataTypeCode.IPAddress)
61 | obj = new IpAddress ();
62 | else if (asnType == SMIDataTypeCode.ObjectId)
63 | obj = new Oid ();
64 | else if (asnType == SMIDataTypeCode.PartyClock)
65 | obj = new V2PartyClock ();
66 | else if (asnType == SMIDataTypeCode.NoSuchInstance)
67 | obj = new NoSuchInstance ();
68 | else if (asnType == SMIDataTypeCode.NoSuchObject)
69 | obj = new NoSuchObject ();
70 | else if (asnType == SMIDataTypeCode.EndOfMibView)
71 | obj = new EndOfMibView ();
72 | else if (asnType == SMIDataTypeCode.Null)
73 | {
74 | obj = new Null ();
75 | }
76 |
77 | return obj;
78 | }
79 | ///
80 | /// Return SNMP type object of the type specified by name. Supported variable types are:
81 | /// , , , ,
82 | /// , , , , and
83 | /// .
84 | ///
85 | /// Type names are the same as support class names compared without case sensitivity (e.g. Integer == INTEGER).
86 | ///
87 | /// Name of the object type (not case sensitive)
88 | /// New object.
89 | public static AsnType GetSyntaxObject (string name)
90 | {
91 | AsnType obj = null;
92 | if (name.ToUpper ().Equals ("INTEGER32") || name.ToUpper ().Equals ("INTEGER"))
93 | obj = new Integer32 ();
94 | else if (name.ToUpper ().Equals ("COUNTER32"))
95 | obj = new Counter32 ();
96 | else if (name.ToUpper ().Equals ("GAUGE32"))
97 | obj = new Gauge32 ();
98 | else if (name.ToUpper ().Equals ("COUNTER64"))
99 | obj = new Counter64 ();
100 | else if (name.ToUpper ().Equals ("TIMETICKS"))
101 | obj = new TimeTicks ();
102 | else if (name.ToUpper ().Equals ("OCTETSTRING"))
103 | obj = new OctetString ();
104 | else if (name.ToUpper ().Equals ("IPADDRESS"))
105 | obj = new IpAddress ();
106 | else if (name.ToUpper ().Equals ("OID"))
107 | obj = new Oid ();
108 | else if (name.ToUpper ().Equals ("NULL"))
109 | obj = new Null ();
110 | else
111 | throw new ArgumentException ("Invalid value type name");
112 |
113 | return obj;
114 | }
115 | ///
116 | /// Return string representation of the SMI value type.
117 | ///
118 | /// AsnType class Type member function value.
119 | /// String formatted name of the SMI type.
120 | public static string GetTypeName (SMIDataTypeCode type)
121 | {
122 | return SMIDataTypeCode.GetName (typeof(SMIDataTypeCode), type);
123 | }
124 | ///
125 | /// Check if byte code is a valid SMI data type code
126 | ///
127 | /// SMI data type code to test
128 | /// true if valid SMI data type, otherwise false
129 | public static bool IsValidType (byte smiType)
130 | {
131 | byte[] validSMITypes = (byte[])Enum.GetValues (typeof(SMIDataTypeCode));
132 | foreach (int type in validSMITypes) {
133 | if (type == smiType)
134 | return true;
135 | }
136 | return false;
137 | }
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/SMIDataTypeCode.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 |
18 | namespace SnmpSharpNet
19 | {
20 | ///
21 | /// Enumeration of SMI type codes used in TLV (Type Length Value) BER encoding of SNMP packets.
22 | ///
23 | public enum SMIDataTypeCode: byte
24 | {
25 | /// Signed 32-bit integer ASN.1 data type. For implementation, see
26 | Integer = (byte)0x02,
27 |
28 | /// Data type representing a sequence of zero or more 8-bit byte values. For implementation, see
29 | OctetString = (byte)0x04,
30 |
31 | /// Object id ASN.1 type. For implementation, see
32 | ObjectId = (byte)0x06,
33 |
34 | /// Null ASN.1 value type. For implementation, see .
35 | Null = (byte)0x05,
36 |
37 | /// An application string is a sequence of octets
38 | /// defined at the application level. Although the SMI
39 | /// does not define an Application String, it does define
40 | /// an IP Address which is an Application String of length
41 | /// four.
42 | ///
43 | AppString = (byte)0x40,
44 |
45 | /// An IP Address is an application string of length four
46 | /// and is indistinguishable from the APPSTRING value.
47 | /// The address is a 32-bit quantity stored in network byte order.
48 | ///
49 | IPAddress = (byte)0x40,
50 |
51 | /// A non-negative integer that may be incremented, but not
52 | /// decremented. The value is a 32-bit unsigned quantity representing
53 | /// the range of zero to 2^32-1 (4,294,967,295). When the counter
54 | /// reaches its maximum value it wraps back to zero and starts again.
55 | ///
56 | Counter32 = (byte)0x41,
57 |
58 | /// Represents a non-negative integer that may increase or
59 | /// decrease with a maximum value of 2^32-1. If the maximum
60 | /// value is reached the gauge stays latched until reset.
61 | ///
62 | Gauge32 = (byte)0x42,
63 |
64 | /// Used to represent the integers in the range of 0 to 2^32-1.
65 | /// This type is identical to the COUNTER32 and are
66 | /// indistinguishable in ASN.1
67 | ///
68 | Unsigned32 = (byte)0x42, // same as gauge
69 |
70 | /// This represents a non-negative integer that counts time, modulo 2^32.
71 | /// The time is represented in hundredths (1/100th) of a second.
72 | ///
73 | TimeTicks = (byte)0x43,
74 |
75 | /// Used to support the transport of arbitrary data. The
76 | /// data itself is encoded as an octet string, but may be in
77 | /// any format defined by ASN.1 or another standard.
78 | ///
79 | Opaque = (byte)0x44,
80 |
81 | /// Defines a 64-bit unsigned counter. A counter is an integer that
82 | /// can be incremented, but cannot be decremented. A maximum value
83 | /// of 2^64 - 1 (18,446,744,073,709,551,615) can be represented.
84 | /// When the counter reaches it's maximum it wraps back to zero and
85 | /// starts again.
86 | ///
87 | Counter64 = (byte)0x46, // SMIv2 only
88 |
89 | /// The SNMPv2 error representing that there is No-Such-Object
90 | /// for a particular object identifier. This error is the result
91 | /// of a requested object identifier that does not exist in the
92 | /// agent's tables
93 | ///
94 | NoSuchObject = (byte)0xc0,
95 |
96 | /// The SNMPv2 error representing that there is No-Such-Instance
97 | /// for a particular object identifier. This error is the result
98 | /// of a requested object identifier instance does not exist in the
99 | /// agent's tables.
100 | ///
101 | NoSuchInstance = (byte)0xc1,
102 |
103 | /// The SNMPv2 error representing the End-Of-Mib-View.
104 | /// This error variable will be returned by a SNMPv2 agent
105 | /// if the requested object identifier has reached the
106 | /// end of the agent's mib table and there is no lexicographic
107 | /// successor.
108 | ///
109 | EndOfMibView = (byte)0xc2,
110 |
111 | ///
112 | /// SEQUENCE Variable Binding code. Hex value: 0x30
113 | ///
114 | Sequence = (byte)0x30,
115 |
116 | /// Defines an SNMPv2 Party Clock. The Party Clock is currently
117 | /// Obsolete, but included for backwards compatibility. Obsoleted in RFC 1902.
118 | ///
119 | PartyClock = (byte)0x47
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/Snmp.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace SnmpSharpNet
6 | {
7 | public class Snmp:UdpTransport
8 | {
9 | ///
10 | /// Internal event to send result of the async request to.
11 | ///
12 | protected event SnmpAsyncResponse _response;
13 | ///
14 | /// Internal storage for request target information.
15 | ///
16 | protected ITarget _target;
17 |
18 | #region Constructor(s)
19 |
20 | ///
21 | /// Constructor
22 | ///
23 | public Snmp()
24 | :base()
25 | {
26 | _response = null;
27 | _target = null;
28 | }
29 |
30 | #endregion Constructor(s)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/SnmpError.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | /// Helper returns error messages for SNMP v1 and v2 error codes
20 | ///
21 | /// Helper class provides translation of SNMP version 1 and 2 error status codes to short, descriptive
22 | /// error messages.
23 | ///
24 | /// To use, call the static member .
25 | ///
26 | /// Example:
27 | /// Console.WriteLine("Agent error: {0}",SnmpError.ErrorMessage(12));
28 | ///
29 | public sealed class SnmpError
30 | {
31 | ///
32 | /// Return SNMP version 1 and 2 error code (errorCode field in the class) as
33 | /// a short, descriptive string.
34 | ///
35 | /// Error code sent by the agent
36 | /// Short error message for the error code
37 | public static string ErrorMessage(int errorCode)
38 | {
39 | if (errorCode == SnmpConstants.ErrNoError)
40 | return "No error";
41 | else if (errorCode == SnmpConstants.ErrTooBig)
42 | return "Request too big";
43 | else if (errorCode == SnmpConstants.ErrNoSuchName)
44 | return "noSuchName";
45 | else if (errorCode == SnmpConstants.ErrBadValue)
46 | return "badValue";
47 | else if (errorCode == SnmpConstants.ErrReadOnly)
48 | return "readOnly";
49 | else if (errorCode == SnmpConstants.ErrGenError)
50 | return "genericError";
51 | else if (errorCode == SnmpConstants.ErrNoAccess)
52 | return "noAccess";
53 | else if (errorCode == SnmpConstants.ErrWrongType)
54 | return "wrongType";
55 | else if (errorCode == SnmpConstants.ErrWrongLength)
56 | return "wrongLength";
57 | else if (errorCode == SnmpConstants.ErrWrongEncoding)
58 | return "wrongEncoding";
59 | else if (errorCode == SnmpConstants.ErrWrongValue)
60 | return "wrongValue";
61 | else if (errorCode == SnmpConstants.ErrNoCreation)
62 | return "noCreation";
63 | else if (errorCode == SnmpConstants.ErrInconsistentValue)
64 | return "inconsistentValue";
65 | else if (errorCode == SnmpConstants.ErrResourceUnavailable)
66 | return "resourceUnavailable";
67 | else if (errorCode == SnmpConstants.ErrCommitFailed)
68 | return "commitFailed";
69 | else if (errorCode == SnmpConstants.ErrUndoFailed)
70 | return "undoFailed";
71 | else if (errorCode == SnmpConstants.ErrAuthorizationError)
72 | return "authorizationError";
73 | else if (errorCode == SnmpConstants.ErrNotWritable)
74 | return "notWritable";
75 | else if (errorCode == SnmpConstants.ErrInconsistentName)
76 | return "inconsistentName";
77 | else
78 | return string.Format("Unknown error ({0})", errorCode);
79 | }
80 |
81 | ///
82 | /// Private constructor.
83 | ///
84 | private SnmpError()
85 | {
86 | }
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/SnmpPacket.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 |
18 | namespace SnmpSharpNet
19 | {
20 | /// Base SNMP packet class.
21 | ///
22 | /// All SNMP packets begin with the SMI_SEQUENCE header and SNMP protocol version number.
23 | /// This class parses and encodes these values. Derived classes parse further information from SNMP packets.
24 | ///
25 | public abstract class SnmpPacket
26 | {
27 | ///
28 | /// SNMP protocol version
29 | ///
30 | protected Integer32 _protocolVersion;
31 | ///
32 | /// SNMP Protocol version
33 | ///
34 | public SnmpVersion Version
35 | {
36 | get
37 | {
38 | return (SnmpVersion)_protocolVersion.Value;
39 | }
40 | }
41 | ///
42 | /// Get Pdu
43 | ///
44 | public virtual Pdu Pdu
45 | {
46 | get
47 | {
48 | return null;
49 | }
50 | }
51 | ///
52 | /// Constructor. Sets SNMP version to SNMPV1.
53 | ///
54 | public SnmpPacket()
55 | {
56 | _protocolVersion = new Integer32((int)SnmpVersion.Ver1);
57 | }
58 | ///
59 | /// Constructor. Initialize SNMP version as supplied.
60 | ///
61 | /// Protocol version. Acceptable values are SnmpConstants.SNMPV1,
62 | /// SnmpConstants.SNMPV2 and SnmpConstants.SNMPV3
63 | public SnmpPacket(SnmpVersion protocolVersion)
64 | {
65 | _protocolVersion = new Integer32((int)protocolVersion);
66 | }
67 | ///
68 | /// Decode SNMP packet header. This class decodes the initial sequence and SNMP protocol version
69 | /// number.
70 | ///
71 | /// BER encoded SNMP packet
72 | /// Packet length
73 | /// Offset position after the initial sequence header and protocol version value
74 | /// Thrown when invalid sequence type is found at the start of the SNMP packet being decoded
75 | public virtual int decode(byte[] buffer, int length)
76 | {
77 | int offset = 0;
78 | if (length < 2)
79 | {
80 | // we need at least 2 bytes
81 | throw new OverflowException("Packet too small.");
82 | }
83 | // make sure you get the right length buffer to be able to check for over/under flow errors
84 | MutableByte buf = new MutableByte(buffer, length);
85 | Sequence seq = new Sequence();
86 | offset = seq.decode(buf, offset);
87 | if( seq.Type != SnmpConstants.SMI_SEQUENCE )
88 | throw new SnmpDecodingException("Invalid sequence type at the start of the SNMP packet.");
89 | offset = _protocolVersion.decode(buf, offset);
90 | return offset;
91 | }
92 | ///
93 | /// Place holder for derived class implementations.
94 | ///
95 | /// Nothing
96 | public abstract byte[] encode();
97 |
98 | ///
99 | /// Wrap BER encoded SNMP information contained in the parameter class.
100 | ///
101 | /// Information in the parameter is prepended by the SNMP version field and wrapped in a sequence header.
102 | ///
103 | /// Derived classes call this method to finalize SNMP packet encoding.
104 | ///
105 | /// Buffer containing BER encoded SNMP information
106 | public virtual void encode(MutableByte buffer)
107 | {
108 | // Encode SNMP protocol version
109 | MutableByte temp = new MutableByte();
110 | _protocolVersion.encode(temp);
111 | buffer.Prepend(temp);
112 | temp.Reset();
113 | AsnType.BuildHeader(temp, SnmpConstants.SMI_SEQUENCE, buffer.Length);
114 | buffer.Prepend(temp);
115 | }
116 | ///
117 | /// Get SNMP protocol version from the packet. This routine does not verify if version number is valid. Caller
118 | /// should verify that returned value represents a valid SNMP protocol version number.
119 | ///
120 | ///
121 | /// int protocolVersion = Packet.GetProtocolVersion(inPacket, inLength);
122 | /// if( protocolVersion != -1 )
123 | /// {
124 | /// if( protocolVersion == SnmpConstants.SNMPV1 || protocolVersion == SnmpConstants.SNMPV2 || protocolVersion == SnmpConstants.SNMPV3 )
125 | /// {
126 | /// // do something
127 | /// }
128 | /// else
129 | /// {
130 | /// Console.WriteLine("Invalid SNMP protocol version.");
131 | /// }
132 | /// }
133 | /// else
134 | /// {
135 | /// Console.WriteLine("Invalid SNMP packet.");
136 | /// }
137 | ///
138 | ///
139 | /// BER encoded SNMP packet
140 | /// Length of the BER encoded packet
141 | /// Returns SNMP protocol version, if packet is not valid returned value is -1.
142 | /// Thrown when invalid sequence type is found at the start of the SNMP packet being decoded
143 | public static int GetProtocolVersion(byte[] buffer, int bufferLength)
144 | {
145 | int offset = 0;
146 | int length = 0;
147 | byte asnType = AsnType.ParseHeader(buffer, ref offset, out length);
148 | if ((offset + length) > bufferLength)
149 | {
150 | return -1; // This is not a valid packet
151 | }
152 | if( asnType != SnmpConstants.SMI_SEQUENCE )
153 | throw new SnmpDecodingException("Invalid sequence type at the start of the SNMP packet.");
154 | Integer32 version = new Integer32();
155 | offset = version.decode(buffer, offset);
156 | return version.Value;
157 | }
158 |
159 | #region Packet type check properties
160 |
161 | ///
162 | /// Packet is a report
163 | ///
164 | public bool IsReport
165 | {
166 | get
167 | {
168 | if (Pdu.Type == PduType.Response)
169 | return true;
170 | return false;
171 | }
172 | }
173 |
174 | ///
175 | /// Packet is a request
176 | ///
177 | ///
178 | /// Checks if the class content is a SNMP Get, GetNext, GetBulk or Set request.
179 | ///
180 | public bool IsRequest
181 | {
182 | get
183 | {
184 | if (Pdu.Type == PduType.Get || Pdu.Type == PduType.GetNext ||
185 | Pdu.Type == PduType.GetBulk || Pdu.Type == PduType.Set)
186 | return true;
187 | return false;
188 | }
189 | }
190 |
191 | ///
192 | /// Packet is a response
193 | ///
194 | public bool IsResponse
195 | {
196 | get
197 | {
198 | if (Pdu.Type == PduType.Response)
199 | return true;
200 | return false;
201 | }
202 | }
203 |
204 | ///
205 | /// Packet is a notification
206 | ///
207 | public bool IsNotification
208 | {
209 | get
210 | {
211 | if (Pdu.Type == PduType.Trap || Pdu.Type == PduType.V2Trap || Pdu.Type == PduType.Inform)
212 | return true;
213 | return false;
214 | }
215 | }
216 | #endregion
217 | }
218 | }
219 |
--------------------------------------------------------------------------------
/SnmpSharpNet.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Debug
5 | AnyCPU
6 | 9.0.21022
7 | 2.0
8 | {8E150D42-5D05-40F8-A388-C3A55EB4A141}
9 | Library
10 | Properties
11 | SnmpSharpNet
12 | SnmpSharpNet
13 | v4.0
14 | 512
15 |
16 |
17 |
18 |
19 | 3.5
20 |
21 | true
22 | keypair.snk
23 |
24 |
25 | true
26 | full
27 | false
28 | bin\Debug\
29 | DEBUG;TRACE
30 | prompt
31 | 4
32 | bin\Debug\SnmpSharpNet.XML
33 | false
34 |
35 |
36 | pdbonly
37 | true
38 | bin\Release\
39 | TRACE
40 | prompt
41 | 4
42 | bin\Release\SnmpSharpNet.XML
43 | false
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
144 |
--------------------------------------------------------------------------------
/SnmpSharpNet.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.25420.1
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SnmpSharpNet", "SnmpSharpNet.csproj", "{8E150D42-5D05-40F8-A388-C3A55EB4A141}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {8E150D42-5D05-40F8-A388-C3A55EB4A141}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {8E150D42-5D05-40F8-A388-C3A55EB4A141}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {8E150D42-5D05-40F8-A388-C3A55EB4A141}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {8E150D42-5D05-40F8-A388-C3A55EB4A141}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | EndGlobal
23 |
--------------------------------------------------------------------------------
/SnmpV1PduErrorStatus.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | /// Snmp V1 error values
20 | public enum SnmpV1PduErrorStatus: int
21 | {
22 | /// Unknown error code received.
23 | Unknown = -1,
24 | /// No error
25 | NoError = 0,
26 | /// Request too big
27 | TooBig = 1,
28 | /// Object identifier does not exist
29 | NoSuchName = 2,
30 | /// Invalid value
31 | BadValue = 3,
32 | /// Requested invalid operation on a read only table
33 | ReadOnly = 4,
34 | /// Generic error
35 | GenError = 5,
36 | /// Enterprise specific error
37 | EnterpriseSpecific = 6,
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/SnmpV1TrapGenericErrorCode.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY, without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 |
18 | namespace SnmpSharpNet
19 | {
20 | /// SNMP version 1 trap generic error code enumeration
21 | public enum SnmpV1TrapGenericErrorCode: int
22 | {
23 | /// Cold start trap
24 | ColdStart = 0,
25 |
26 | /// Warm start trap
27 | WarmStart = 1,
28 |
29 | /// Link down trap
30 | LinkDown = 2,
31 |
32 | /// Link up trap
33 | LinkUp = 3,
34 |
35 | /// Authentication-failure trap
36 | AuthenticationFailure = 4,
37 |
38 | /// EGP Neighbor Loss trap
39 | EgpNeighborLoss = 5,
40 |
41 | /// Enterprise Specific trap
42 | EnterpriseSpecific = 6
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/SnmpV1TrapPacket.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 |
18 | namespace SnmpSharpNet
19 | {
20 | /// SNMP version 1 TRAP packet class.
21 | ///
22 | /// Available packet classes are:
23 | ///
24 | ///
25 | ///
26 | ///
27 | ///
28 | ///
29 | ///
30 | /// This class is provided to simplify encoding and decoding of packets and to provide consistent interface
31 | /// for users who wish to handle transport part of protocol on their own without using the
32 | /// class.
33 | ///
34 | /// and derived classes have been developed to implement SNMP packet support. For
35 | /// SNMP version 1 and 2 packet, and classes provides
36 | /// sufficient support for encoding and decoding data to/from BER buffers to satisfy requirements of most
37 | /// applications.
38 | ///
39 | /// SNMP version 3 on the other hand requires a lot more information to be passed to the encoder method and
40 | /// returned by the decode method. Attempt of implementing SNMP version 3 as part of
41 | /// class was operational but required too many function arguments to operate so a different interface was
42 | /// developed using dedicated class.
43 | ///
44 | public class SnmpV1TrapPacket : SnmpPacket
45 | {
46 | ///
47 | /// SNMP Protocol Data Unit
48 | ///
49 | protected TrapPdu _pdu;
50 |
51 | ///
52 | /// Access to the packet .
53 | ///
54 | public new TrapPdu Pdu
55 | {
56 | get { return _pdu; }
57 | }
58 |
59 | ///
60 | /// Get TrapPdu
61 | ///
62 | public TrapPdu TrapPdu
63 | {
64 | get
65 | {
66 | return _pdu;
67 | }
68 | }
69 |
70 | ///
71 | /// SNMP community name
72 | ///
73 | protected OctetString _snmpCommunity;
74 |
75 | ///
76 | /// Get SNMP community value used by SNMP version 1 and version 2 protocols.
77 | ///
78 | public OctetString Community
79 | {
80 | get { return _snmpCommunity; }
81 | }
82 |
83 | ///
84 | /// Standard constructor.
85 | ///
86 | public SnmpV1TrapPacket()
87 | : base(SnmpVersion.Ver1)
88 | {
89 | _snmpCommunity = new OctetString();
90 | _pdu = new TrapPdu();
91 | }
92 |
93 | ///
94 | /// Standard constructor.
95 | ///
96 | /// SNMP community name for the packet
97 | public SnmpV1TrapPacket(string snmpCommunity)
98 | : this()
99 | {
100 | _snmpCommunity.Set(snmpCommunity);
101 | }
102 |
103 | ///
104 | /// Decode received packet. This method overrides the base implementation that cannot be used with this type of the packet.
105 | ///
106 | /// Packet buffer
107 | /// Buffer length
108 | public override int decode(byte[] buffer, int length)
109 | {
110 | int offset = 0;
111 | MutableByte buf = new MutableByte(buffer, length);
112 |
113 | offset = base.decode(buffer, length);
114 |
115 |
116 | // parse community
117 | offset = _snmpCommunity.decode(buf, offset);
118 |
119 | // look ahead to make sure this is a TRAP packet
120 | int tmpOffset = offset;
121 | int headerLen;
122 | byte tmpAsnType = AsnType.ParseHeader(buffer, ref tmpOffset, out headerLen);
123 | if (tmpAsnType != (byte)PduType.Trap)
124 | {
125 | throw new SnmpException(string.Format("Invalid SNMP ASN.1 type. Received: {0:x2}", tmpAsnType));
126 | }
127 | // decode protocol data unit
128 | offset = this.Pdu.decode(buf, offset);
129 | return offset;
130 | }
131 |
132 | ///
133 | /// Encode SNMP packet for sending.
134 | ///
135 | /// BER encoded SNMP packet.
136 | public override byte[] encode()
137 | {
138 | MutableByte tmpBuffer = new MutableByte();
139 |
140 | //
141 | // encode the community strings
142 | _snmpCommunity.encode(tmpBuffer);
143 | this.Pdu.encode(tmpBuffer);
144 |
145 | base.encode(tmpBuffer);
146 |
147 | return (byte[])tmpBuffer;
148 | }
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/SnmpV2PduErrorStatus.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | /// Snmp V2 error values
20 | public enum SnmpV2PduErrorStatus: int
21 | {
22 | /// Unknown error code received.
23 | Unknown = -1,
24 | /// No error
25 | NoError = 0,
26 | /// Request too big
27 | TooBig = 1,
28 | /// Object identifier does not exist
29 | NoSuchName = 2,
30 | /// Invalid value
31 | BadValue = 3,
32 | /// Requested invalid operation on a read only table
33 | ReadOnly = 4,
34 | /// Generic error
35 | GenError = 5,
36 | /// Access denied
37 | NoAccess = 6,
38 | /// Incorrect type
39 | WrongType = 7,
40 | /// Incorrect length
41 | WrongLength = 8,
42 | /// Invalid encoding
43 | WrongEncoding = 9,
44 | /// Object does not have correct value
45 | WrongValue = 10,
46 | /// Insufficient rights to perform create operation
47 | NoCreation = 11,
48 | /// Inconsistent value
49 | InconsistentValue = 12,
50 | /// Requested resource is not available
51 | ResourceUnavailable = 13,
52 | /// Unable to commit values
53 | CommitFailed = 14,
54 | /// Undo request failed
55 | UndoFailed = 15,
56 | /// Authorization failed
57 | AuthorizationError = 16,
58 | /// Instance not writable
59 | NotWritable = 17,
60 | /// Inconsistent object identifier
61 | InconsistentName = 18
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/SnmpVariableType.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace SnmpSharpNet
6 | {
7 | ///
8 | /// Class containing SNMP type constants usable in switch/case evaluation of variable types.
9 | ///
10 | public sealed class SnmpVariableType
11 | {
12 | ///
13 | /// SNMP type Counter32
14 | ///
15 | public const byte Counter32 = 0x40;
16 | ///
17 | /// SNMP type Counter64
18 | ///
19 | public const byte Counter64 = 0x66;
20 | ///
21 | /// SNMP type EndOfMibView
22 | ///
23 | public const byte EndOfMibView = 0x82;
24 | ///
25 | /// SNMP type Gauge32
26 | ///
27 | public const byte Gauge32 = 0x41;
28 | ///
29 | /// SNMP type Integer
30 | ///
31 | public const byte Integer = 0x02;
32 | ///
33 | /// SNMP type IPAddress
34 | ///
35 | public const byte IPAddress = 0x40;
36 | ///
37 | /// SNMP type NoSuchInstance
38 | ///
39 | public const byte NoSuchInstance = 0x81;
40 | ///
41 | /// SNMP type NoSuchObject
42 | ///
43 | public const byte NoSuchObject = 0x80;
44 | ///
45 | /// SNMP type Null
46 | ///
47 | public const byte Null = 0x05;
48 | ///
49 | /// SNMP type OctetString
50 | ///
51 | public const byte OctetString = 0x04;
52 | ///
53 | /// SNMP type Oid
54 | ///
55 | public const byte Oid = 0x06;
56 | ///
57 | /// SNMP type Opaque
58 | ///
59 | public const byte Opaque = 0x44;
60 | ///
61 | /// SNMP type Sequence
62 | ///
63 | public const byte Sequence = 0x30;
64 | ///
65 | /// SNMP type TimeTicks
66 | ///
67 | public const byte TimeTicks = 0x43;
68 | ///
69 | /// SNMP type Unsigned32
70 | ///
71 | public const byte Unsigned32 = 0x42;
72 | ///
73 | /// SNMP type VarBind
74 | ///
75 | public const byte VarBind = 0x30;
76 |
77 | ///
78 | /// Private constructor to prevent the class with all static members from being instantiated.
79 | ///
80 | private SnmpVariableType()
81 | {
82 | // nothing
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/SnmpVersion.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// SNMP Version number enumeration
21 | ///
22 | public enum SnmpVersion
23 | {
24 | ///
25 | /// SNMP version 1
26 | ///
27 | Ver1 = 0,
28 | ///
29 | /// SNMP version 2c
30 | ///
31 | Ver2 = 1,
32 | ///
33 | /// SNMP version 3
34 | ///
35 | Ver3 = 3
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/Types/Counter32.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | namespace SnmpSharpNet
18 | {
19 | /// SMI Counter32 type implementation.
20 | ///
21 | /// Counter32 value type is a 32-bit unsigned integer object that
22 | /// is incremented by an agent until maximum unsigned integer value
23 | /// is reached. When maximum value is reached, Counter32 value will
24 | /// roll over to 0.
25 | ///
26 | [Serializable]
27 | public class Counter32:UInteger32, System.ICloneable
28 | {
29 | /// Constructor
30 | public Counter32():base()
31 | {
32 | _asnType = SnmpConstants.SMI_COUNTER32;
33 | }
34 |
35 | /// Constructor
36 | /// Copy parameter
37 | public Counter32(Counter32 second):base(second)
38 | {
39 | _asnType = SnmpConstants.SMI_COUNTER32;
40 | }
41 |
42 | /// Constructor
43 | /// UInteger32 value
44 | public Counter32(UInteger32 uint32):base(uint32)
45 | {
46 | _asnType = SnmpConstants.SMI_COUNTER32;
47 | }
48 |
49 | /// Constructor
50 | /// Unsigned integer encoded in a string.
51 | public Counter32(System.String val):base(val)
52 | {
53 | _asnType = SnmpConstants.SMI_COUNTER32;
54 | }
55 |
56 | /// Constructor.
57 | /// UInt32 value
58 | public Counter32(UInt32 val):base(val)
59 | {
60 | _asnType = SnmpConstants.SMI_COUNTER32;
61 | }
62 |
63 | /// Duplicate current object
64 | /// Duplicate of the current object cast as Object class.
65 | public override System.Object Clone()
66 | {
67 | return new Counter32(this);
68 | }
69 |
70 | ///
71 | /// Return difference between two Counter32 values taking counter roll-over into account.
72 | ///
73 | /// First or older value
74 | /// Second or newer value
75 | /// Difference between the two values
76 | public static UInt32 Diff(Counter32 first, Counter32 second)
77 | {
78 | UInt32 f = first.Value;
79 | UInt32 s = second.Value;
80 | UInt32 res = 0;
81 | if (s > f)
82 | {
83 | // in case of a roll-over event
84 | res = (UInt32.MaxValue - f) + s;
85 | }
86 | else
87 | {
88 | res = s - f;
89 | }
90 | return res;
91 | }
92 | }
93 | }
--------------------------------------------------------------------------------
/Types/EndOfMibView.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Returned when end of MIB has been reached when performing GET-NEXT or GET-BULK operations.
21 | ///
22 | [Serializable]
23 | public class EndOfMibView : V2Error, System.ICloneable
24 | {
25 | /// The default class construtor.
26 | public EndOfMibView():base()
27 | {
28 | _asnType = SnmpConstants.SMI_ENDOFMIBVIEW;
29 | }
30 |
31 | /// The class copy constructor.
32 | ///
33 | /// The object to copy into self.
34 | ///
35 | public EndOfMibView(EndOfMibView second):base(second)
36 | {
37 | _asnType = SnmpConstants.SMI_ENDOFMIBVIEW;
38 | }
39 |
40 | /// Returns a duplicate object of self.
41 | ///
42 | /// A duplicate of self
43 | ///
44 | public override Object Clone()
45 | {
46 | return new EndOfMibView(this);
47 | }
48 | /// Decode ASN.1 encoded end-of-mib-view SNMP version 2 MIB value
49 | /// The encoded buffer
50 | /// The offset of the first byte of encoded data
51 | /// Offset after the decoded value
52 | public override int decode(byte[] buffer, int offset)
53 | {
54 | int headerLength;
55 | byte asnType = ParseHeader(buffer, ref offset, out headerLength);
56 | if (asnType != Type)
57 | {
58 | throw new SnmpException("Invalid ASN.1 type");
59 | }
60 |
61 | if (headerLength != 0)
62 | throw new SnmpException("Invalid ASN.1 length");
63 |
64 | return offset;
65 | }
66 |
67 | ///
68 | /// ASN.1 encode end-of-mib-view SNMP version 2 MIB value
69 | ///
70 | /// MutableByte to append encoded variable to
71 | public override void encode(MutableByte buffer)
72 | {
73 | BuildHeader(buffer, Type, 0);
74 | }
75 |
76 | /// Returns the string representation of the object.
77 | ///
78 | /// String prepresentation of the object.
79 | public override String ToString()
80 | {
81 | return "SNMP End-of-MIB-View";
82 | }
83 | }
84 | }
--------------------------------------------------------------------------------
/Types/EthernetAddress.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | using System.Globalization;
18 | namespace SnmpSharpNet
19 | {
20 |
21 | /// EthernetAddress class encapsulates a 6 byte OctetString
22 | /// representing an Ethernet MAC address.
23 | ///
24 | /// THis class doesn't not represent a distinct ASN.1 data type. It is a helper
25 | /// class to allow users to perform MAC address specific operations on OctetString values.
26 | [Serializable]
27 | public class EthernetAddress : OctetString, ICloneable
28 | {
29 | /// Constructor. Initialize the class to 0000.0000.0000
30 | ///
31 | public EthernetAddress()
32 | : base(new byte[] { 0, 0, 0, 0, 0, 0 })
33 | {
34 | }
35 |
36 | ///
37 | /// Constructor. Initialize the class with the value of the byte array.
38 | ///
39 | /// Byte array whose value is used to initialize the class.
40 | ///
41 | public EthernetAddress(byte[] data)
42 | :base(data)
43 | {
44 | if (data.Length < 6)
45 | throw new System.ArgumentException("Buffer underflow error converting IP address");
46 | else if (data.Length > 6)
47 | throw new System.ArgumentException("Buffer overflow error converting IP address");
48 | base.Set(data);
49 | }
50 |
51 | ///
52 | /// Constructor. Initialize the class with the value from the argument class.
53 | ///
54 | /// Class whose value is copied to initialize this class.
55 | ///
56 | public EthernetAddress(EthernetAddress second)
57 | : base()
58 | {
59 | base.Set(second.ToArray());
60 | }
61 |
62 | /// Constructor. Initialize the class with the value from the argument.
63 | ///
64 | /// Class whose value is used to initialize this class.
65 | ///
66 | public EthernetAddress(OctetString second)
67 | : this()
68 | {
69 | if (second.Length < 6)
70 | throw new System.ArgumentException("Buffer underflow error converting IP address");
71 | else if (Length > 6)
72 | throw new System.ArgumentException("Buffer overflow error converting IP address");
73 | base.Set(second);
74 | }
75 |
76 | /// Create a new object that is a duplicate of the
77 | /// current object.
78 | ///
79 | /// A newly created duplicate object.
80 | ///
81 | public override System.Object Clone()
82 | {
83 | return new EthernetAddress(this);
84 | }
85 |
86 | /// Parses hex string representing an Ethernet MAC address to the enternal format. Ethernet
87 | /// address has to contain 12 hex characters (1-9 or A-F) to be parsed correctly. Special formatting is
88 | /// ignored so both 0000.0010.0000 and 00-00-00-10-00-00 will be parsed ok.
89 | ///
90 | /// Ethernet address represented as a string.
91 | ///
92 | public override void Set(System.String value)
93 | {
94 | if( value == null || value.Length <= 0 )
95 | throw new ArgumentException("Invalid argument. String is empty.");
96 | string workString = (string)value.Clone();
97 | for (int cnt = 0; cnt < value.Length; cnt++)
98 | {
99 | if (!Char.IsNumber(workString[cnt]) && Char.ToUpper(workString[cnt]) != 'A' &&
100 | Char.ToUpper(workString[cnt]) != 'B' && Char.ToUpper(workString[cnt]) != 'C' &&
101 | Char.ToUpper(workString[cnt]) != 'D' && Char.ToUpper(workString[cnt]) != 'E' &&
102 | Char.ToUpper(workString[cnt]) != 'F')
103 | {
104 | workString.Remove(cnt, 1);
105 | cnt -= 1;
106 | }
107 | }
108 | if (workString.Length != 12)
109 | {
110 | throw new ArgumentException("Invalid Ethernet address format.");
111 | }
112 | int pos = 0;
113 | int bufpos = 0;
114 | while (pos + 2 < workString.Length)
115 | {
116 | string val = workString.Substring(pos, 2);
117 | byte v = Byte.Parse(val, NumberStyles.HexNumber);
118 | _data[bufpos++] = v;
119 | pos += 2;
120 | }
121 | }
122 |
123 | ///
124 | /// Return Ethernet MAC address as a string formatted as: xxxx.xxxx.xxxx
125 | ///
126 | /// String representation of the object value.
127 | public override System.String ToString()
128 | {
129 | return String.Format(CultureInfo.CurrentCulture,"{0:x2}{1:x2}.{2:x2}{3:x2}.{4:x2}{5:x2}", _data[0], _data[1], _data[2], _data[3], _data[4], _data[5]);
130 | }
131 | }
132 | }
--------------------------------------------------------------------------------
/Types/Gauge32.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | namespace SnmpSharpNet
18 | {
19 | /// ASN.1 Gauge32 value class.
20 | ///
21 | [Serializable]
22 | public class Gauge32:UInteger32, ICloneable
23 | {
24 | /// Constructs the default counter object.
25 | /// The initial value is defined
26 | /// by the super class default constructor
27 | ///
28 | public Gauge32():base()
29 | {
30 | _asnType = SnmpConstants.SMI_GAUGE32;
31 | }
32 |
33 |
34 | /// Constructs a new object with the same value
35 | /// as the passed object.
36 | ///
37 | /// The object to recover values from.
38 | ///
39 | public Gauge32(Gauge32 second):base(second)
40 | {
41 | _asnType = SnmpConstants.SMI_GAUGE32;
42 | }
43 |
44 | /// Constructs a new object with the value
45 | /// constrained in the UInteger32 object.
46 | ///
47 | /// The UInteger32 object to copy.
48 | ///
49 | public Gauge32(UInteger32 uint32):base(uint32)
50 | {
51 | _asnType = SnmpConstants.SMI_GAUGE32;
52 | }
53 |
54 | /// Constructor. Initialize class value with the unsigned integer 32-bit value
55 | /// encoded as string in the argument.
56 | ///
57 | /// 32-bit unsigned integer encoded as a string
58 | ///
59 | public Gauge32(System.String val):base(val)
60 | {
61 | _asnType = SnmpConstants.SMI_GAUGE32;
62 | }
63 |
64 | ///
65 | /// Constructor
66 | ///
67 | /// Initializing value
68 | public Gauge32(UInt32 val):base(val)
69 | {
70 | _asnType = SnmpConstants.SMI_GAUGE32;
71 | }
72 |
73 | /// Duplicate current object.
74 | ///
75 | /// Copy of the object.
76 | public override System.Object Clone()
77 | {
78 | return new Gauge32(this);
79 | }
80 | }
81 | }
--------------------------------------------------------------------------------
/Types/NoSuchInstance.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | namespace SnmpSharpNet
18 | {
19 |
20 |
21 | /// SNMPv2 noSuchInstance error
22 | ///
23 | /// Returned when requested instance is not present in a table of the SNMP version 2 agent.
24 | ///
25 | /// This type is returned as value to a requested Oid. When looping through results, check Vb.Value
26 | /// member for V2Error returns.
27 | ///
28 | [Serializable]
29 | public class NoSuchInstance : V2Error, ICloneable
30 | {
31 | /// Constructor.
32 | public NoSuchInstance():base()
33 | {
34 | _asnType = SnmpConstants.SMI_NOSUCHINSTANCE;
35 | }
36 |
37 | /// Constructor.
38 | /// The object to copy into self.
39 | public NoSuchInstance(NoSuchInstance second):base(second)
40 | {
41 | _asnType = SnmpConstants.SMI_NOSUCHINSTANCE;
42 | }
43 |
44 | /// Returns a duplicate object of self.
45 | /// A duplicate of self
46 | public override System.Object Clone()
47 | {
48 | return new NoSuchInstance(this);
49 | }
50 |
51 | /// Decode BER encoded no-such-instance SNMP version 2 MIB value
52 | /// The BER encoded buffer
53 | /// The offset of the first byte of encoded data
54 | /// Buffer position after the decoded value
55 | /// Invalid ASN.1 type found when parsing value header
56 | /// Invalid data length in ASN.1 header. Only data length 0 is accepted.
57 | public override int decode(byte[] buffer, int offset)
58 | {
59 | int headerLength;
60 | byte asnType = ParseHeader(buffer, ref offset, out headerLength);
61 | if (asnType != Type)
62 | throw new SnmpException("Invalid ASN.1 type");
63 |
64 | if (headerLength != 0)
65 | throw new SnmpDecodingException("Invalid ASN.1 length");
66 |
67 | return offset;
68 | }
69 |
70 | ///
71 | /// ASN.1 encode no-such-instance SNMP version 2 MIB value
72 | ///
73 | /// MutableByte reference to append encoded variable to
74 | public override void encode(MutableByte buffer)
75 | {
76 | BuildHeader(buffer, Type, 0);
77 | }
78 |
79 | /// Returns the string representation of the object.
80 | /// String representatio of the class
81 | public override System.String ToString()
82 | {
83 | return "SNMP No-Such-Instance";
84 | }
85 | }
86 | }
--------------------------------------------------------------------------------
/Types/NoSuchObject.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | namespace SnmpSharpNet
18 | {
19 |
20 |
21 | /// SNMPv2 NoSuchObject error
22 | ///
23 | /// NoSuchObject is returned by the agent in response to a SNMP version 2 request
24 | /// when requested object does not exist in its MIB.
25 | /// This value is returned as a with data of length 0
26 | ///
27 | /// For example:
28 | ///
29 | /// // [... prepare for a get operation ...]
30 | /// Pdu response = target.Request(outpdu, params);
31 | /// foreach(Vb vb in response.VbList) {
32 | /// if( vb.Value is NoSuchObject ) {
33 | /// return "Requested MIB variable does not exist on the agent.";
34 | /// }
35 | /// }
36 | ///
37 | ///
38 | [Serializable]
39 | public class NoSuchObject:V2Error, ICloneable
40 | {
41 |
42 | /// Constructor.
43 | public NoSuchObject():base()
44 | {
45 | _asnType = SnmpConstants.SMI_NOSUCHOBJECT;
46 | }
47 | ///
48 | /// Constructor
49 | ///
50 | ///
51 | /// Source for data to initialize this instance with.
52 | ///
53 | /// Irrelevant for this type since no data is stored in the class.
54 | ///
55 | public NoSuchObject(NoSuchObject second):base(second)
56 | {
57 | }
58 |
59 | /// Returns a duplicate object of self.
60 | /// A duplicate of self
61 | public override Object Clone()
62 | {
63 | // just create a new object. it doesn't hold any data anyway
64 | return new NoSuchObject();
65 | }
66 |
67 | /// Decode ASN.1 encoded no-such-object SNMP version 2 MIB value
68 | /// The encoded buffer
69 | /// The offset of the first byte of encoded data
70 | /// Buffer position after the decoded value
71 | public override int decode(byte[] buffer, int offset)
72 | {
73 | int headerLength;
74 | byte asnType = ParseHeader(buffer, ref offset, out headerLength);
75 | if (asnType != Type)
76 | throw new SnmpException("Invalid ASN.1 type");
77 |
78 | if (headerLength != 0)
79 | throw new SnmpException("Invalid ASN.1 length");
80 |
81 | return offset;
82 | }
83 |
84 | ///
85 | /// ASN.1 encode no-such-object SNMP version 2 MIB value
86 | ///
87 | /// MutableByte reference to append encoded variable to
88 | public override void encode(MutableByte buffer)
89 | {
90 | BuildHeader(buffer, Type, 0);
91 | }
92 |
93 | /// Returns the string representation of the object.
94 | /// String representation of the class
95 | public override System.String ToString()
96 | {
97 | return "SNMP No-Such-Object";
98 | }
99 | }
100 | }
--------------------------------------------------------------------------------
/Types/Null.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | namespace SnmpSharpNet
18 | {
19 |
20 | /// ASN.1 Null value implementation.
21 | [Serializable]
22 | public class Null : AsnType, ICloneable
23 | {
24 | /// Constructor
25 | public Null()
26 | {
27 | _asnType = SnmpConstants.SMI_NULL;
28 | }
29 |
30 | /// Constructor
31 | /// Irrelevant. Nothing to copy
32 | public Null(Null second) : this()
33 | {
34 | }
35 |
36 | #region Encode & decode methods
37 |
38 | ///
39 | /// ASN.1 encode Null value
40 | ///
41 | /// class to the end of which encoded data is appended
42 | ///
43 | public override void encode(MutableByte buffer)
44 | {
45 | BuildHeader(buffer, Type, 0);
46 | }
47 |
48 | ///
49 | /// Decode null value from BER encoded buffer.
50 | ///
51 | /// BER encoded buffer
52 | /// Offset within the buffer from where to start decoding. On return,
53 | /// this argument contains the offset immediately following the decoded value.
54 | ///
55 | /// Buffer position after the decoded value
56 | /// Thrown when parsed ASN.1 type is not null
57 | /// Thrown when length of null value is greater then 0 bytes
58 | public override int decode(byte[] buffer, int offset)
59 | {
60 | int headerLength;
61 | byte asnType = ParseHeader(buffer, ref offset, out headerLength);
62 |
63 | if (asnType != Type)
64 | throw new SnmpException("Invalid ASN.1 Type");
65 |
66 | // Verify length is 0
67 | if (headerLength != 0)
68 | throw new SnmpException("Malformed ASN.1 Type");
69 |
70 | return offset;
71 | }
72 |
73 | #endregion Encode & decode methods
74 |
75 | /// Clone current object
76 | /// Duplicate of the current object.
77 | public override Object Clone()
78 | {
79 | return new Null(this);
80 | }
81 |
82 | /// Returns a string representation of the SNMP NULL object
83 | /// String representation of the class
84 | public override System.String ToString()
85 | {
86 | return "Null";
87 | }
88 | }
89 | }
--------------------------------------------------------------------------------
/Types/Opaque.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | using System.Text;
18 | namespace SnmpSharpNet
19 | {
20 |
21 |
22 | /// Opaque type is an application-wide type supports the capability to pass arbitrary
23 | /// ASN.1 syntax
24 | /// SMIv2 defines Opaque type as provided solely for backward-compatibility, and
25 | /// shall not be used for newly-defined object types
26 | [Serializable]
27 | public class Opaque : OctetString, System.ICloneable
28 | {
29 | /// Constructor
30 | public Opaque():base()
31 | {
32 | _asnType = SnmpConstants.SMI_OPAQUE;
33 | }
34 |
35 | /// Constructor
36 | /// Data
37 | public Opaque(byte[] data):base(data)
38 | {
39 | _asnType = SnmpConstants.SMI_OPAQUE;
40 | }
41 |
42 | /// Copy constructor
43 | /// The object to be duplicated.
44 | public Opaque(Opaque second):base(second)
45 | {
46 | _asnType = SnmpConstants.SMI_OPAQUE;
47 | }
48 |
49 | /// Constructor
50 | /// The object to be duplicated.
51 | public Opaque(OctetString second)
52 | : base(second)
53 | {
54 | _asnType = SnmpConstants.SMI_OPAQUE;
55 | }
56 |
57 | ///
58 | /// Constructor
59 | ///
60 | /// Initializer value
61 | public Opaque(string value)
62 | : base(value)
63 | {
64 | _asnType = SnmpConstants.SMI_OPAQUE;
65 | }
66 |
67 | /// Returns a duplicate of the current object.
68 | /// Copy of the current object cast as Object
69 | public override Object Clone()
70 | {
71 | return new Opaque(this);
72 | }
73 | }
74 | }
--------------------------------------------------------------------------------
/Types/Sequence.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace SnmpSharpNet
6 | {
7 | ///
8 | /// Represents SNMP sequence
9 | ///
10 | [Serializable]
11 | public class Sequence : AsnType, ICloneable
12 | {
13 | ///
14 | /// data buffer
15 | ///
16 | protected byte[] _data;
17 |
18 | ///
19 | /// Constructor
20 | ///
21 | public Sequence() :
22 | base()
23 | {
24 | _asnType = SnmpConstants.SMI_SEQUENCE;
25 | _data = null;
26 |
27 | }
28 |
29 | ///
30 | /// Constructor.
31 | ///
32 | /// Sequence data
33 | public Sequence(byte[] value)
34 | : this()
35 | {
36 | if (value != null && value.Length > 0)
37 | {
38 | _data = new byte[value.Length];
39 | Buffer.BlockCopy(value, 0, _data, 0, value.Length);
40 | }
41 | }
42 |
43 | ///
44 | /// Set sequence data
45 | ///
46 | /// Byte array containing BER encoded sequence data
47 | public void Set(byte[] value)
48 | {
49 | if (value == null || value.Length <= 0)
50 | _data = null;
51 | else
52 | {
53 | _data = new byte[value.Length];
54 | Buffer.BlockCopy(value, 0, _data, 0, value.Length);
55 | }
56 | }
57 |
58 | ///
59 | /// BER encode sequence
60 | ///
61 | /// Target buffer
62 | public override void encode(MutableByte buffer)
63 | {
64 | int dataLen = 0;
65 | if (_data != null && _data.Length > 0)
66 | dataLen = _data.Length;
67 | BuildHeader(buffer, Type, dataLen);
68 | if (dataLen > 0)
69 | buffer.Append(_data);
70 | }
71 |
72 | ///
73 | /// Decode sequence from the byte array. Returned offset value is advanced by the size of the sequence header.
74 | ///
75 | /// Source data buffer
76 | /// Offset within the buffer to start parsing from
77 | /// Returns offset position after the sequence header
78 | public override int decode(byte[] buffer, int offset)
79 | {
80 | _data = null;
81 | int dataLen = 0;
82 | int asnType = ParseHeader(buffer, ref offset, out dataLen);
83 | if (asnType != Type)
84 | throw new SnmpException("Invalid ASN.1 type.");
85 | if (offset + dataLen > buffer.Length)
86 | throw new OverflowException("Sequence longer then packet.");
87 | if (dataLen > 0)
88 | {
89 | _data = new byte[dataLen];
90 | Buffer.BlockCopy(buffer, offset, _data, 0, dataLen);
91 | }
92 | return offset;
93 | }
94 |
95 | ///
96 | /// Get sequence data
97 | ///
98 | public byte[] Value
99 | {
100 | get
101 | {
102 | return _data;
103 | }
104 | }
105 |
106 | ///
107 | /// Clone sequence
108 | ///
109 | /// Cloned sequence cast as object
110 | public override object Clone()
111 | {
112 | return (object)new Sequence(_data);
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/Types/TimeTicks.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | namespace SnmpSharpNet
18 | {
19 |
20 |
21 | /// SMI TimeTicks class
22 | ///
23 | /// TimeTicks value is stored as an unsigned
24 | /// 32-bit integer representing device uptime in 1/100s of a second time periods.
25 | ///
26 | [Serializable]
27 | public class TimeTicks:UInteger32,ICloneable
28 | {
29 | /// Constructor
30 | public TimeTicks():base()
31 | {
32 | _asnType = (byte)SnmpConstants.SMI_TIMETICKS;
33 | }
34 |
35 | /// Constructor
36 | /// Initialize class with value from this class.
37 | public TimeTicks(TimeTicks second):base(second)
38 | {
39 | _asnType = (byte)SnmpConstants.SMI_TIMETICKS;
40 | }
41 |
42 | /// Constructor
43 | /// The UInteger32 value to initialize the class with.
44 | public TimeTicks(UInteger32 uint32):base(uint32)
45 | {
46 | _asnType = (byte)SnmpConstants.SMI_TIMETICKS;
47 | }
48 |
49 | ///
50 | /// Constructor.
51 | ///
52 | /// Initialize the TimeTicks class to this unsigned integer value.
53 | public TimeTicks(UInt32 value)
54 | : base(value)
55 | {
56 | _asnType = (byte)SnmpConstants.SMI_TIMETICKS;
57 | }
58 |
59 | ///
60 | /// Constructor
61 | ///
62 | /// String holding 32-bit unsigned integer value to initialize the class with
63 | ///
64 | public TimeTicks(System.String val):base(val)
65 | {
66 | _asnType = (byte)SnmpConstants.SMI_TIMETICKS;
67 | }
68 |
69 | /// Duplicate object
70 | /// Object cloned copy cast to Object
71 | public override System.Object Clone()
72 | {
73 | return new TimeTicks(this);
74 | }
75 |
76 | ///
77 | /// Operator to allow explicit conversion of TimeTicks class to a TimeSpan class.
78 | ///
79 | /// TimeTicks class to convert to TimeSpan
80 | /// TimeSpan value representing the value of TimeTicks class.
81 | public static explicit operator TimeSpan(TimeTicks value) {
82 | Int64 ticks = value.Value;
83 | ticks *= 10;
84 | ticks *= 10000;
85 | TimeSpan ts = new TimeSpan(ticks);
86 | return ts;
87 | }
88 |
89 | ///
90 | /// Get TimeTicks value as milliseconds value.
91 | ///
92 | public Int64 Milliseconds
93 | {
94 | get
95 | {
96 | Int64 ttval = Convert.ToInt64(_value);
97 | Int64 res = ttval * 10L;
98 | return res;
99 | }
100 | }
101 |
102 | ///
103 | /// Returns the string representation of the object.
104 | ///
105 | /// String representation of the class value.
106 | public override System.String ToString()
107 | {
108 | System.Text.StringBuilder buf = new System.Text.StringBuilder();
109 | long time = Value;
110 | long tmp = 0;
111 | if ((tmp = (time / (24 * 3600 * 100))) > 0)
112 | {
113 | buf.Append(tmp).Append("d ");
114 | time = time % (24 * 3600 * 100);
115 | }
116 | else
117 | buf.Append("0d ");
118 |
119 | if ((tmp = time / (3600 * 100)) > 0)
120 | {
121 | buf.Append(tmp).Append("h ");
122 | time = time % (3600 * 100);
123 | }
124 | else
125 | buf.Append("0h ");
126 |
127 | if ((tmp = time / 6000) > 0)
128 | {
129 | buf.Append(tmp).Append("m ");
130 | time = time % 6000;
131 | }
132 | else
133 | buf.Append("0m ");
134 |
135 | if ((tmp = time / 100) > 0)
136 | {
137 | buf.Append(tmp).Append("s ");
138 | time = time % 100;
139 | }
140 | else
141 | buf.Append("0s ");
142 |
143 | buf.Append(time * 10).Append("ms");
144 |
145 | return buf.ToString();
146 | }
147 | ///
148 | /// Return hash code for the class.
149 | ///
150 | /// Hash code is the hash code of the class value.
151 | public override int GetHashCode()
152 | {
153 | return _value.GetHashCode();
154 | }
155 | }
156 | }
--------------------------------------------------------------------------------
/Types/V2Error.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | namespace SnmpSharpNet
18 | {
19 |
20 | /// Base class for SNMP version 2 error types.
21 | ///
22 | /// For details see , and .
23 | ///
24 | public class V2Error : AsnType, ICloneable
25 | {
26 | ///
27 | /// Constructor
28 | ///
29 | public V2Error()
30 | {
31 | // do nothing
32 | }
33 |
34 | /// Constructor.
35 | ///
36 | /// Since this class doesn't hold any meaningful information, constructor
37 | /// does nothing with the argument.
38 | ///
39 | /// Second object
40 | public V2Error(V2Error second)
41 | {
42 | }
43 |
44 | /// BER encode SNMP version 2 error.
45 | /// Buffer to append encoded value to the end of
46 | public override void encode(MutableByte buffer)
47 | {
48 | BuildHeader(buffer, Type, 0);
49 | }
50 |
51 | /// Decode BER encoded SNMP version 2 error.
52 | /// BER encoded buffer
53 | /// Offset within the buffer to start decoding the value from. This argument will
54 | /// receive the new offset to the byte immediately following the decoded value.
55 | /// Buffer position after the decoded value
56 | public override int decode(byte[] buffer, int offset)
57 | {
58 | int headerLength;
59 | byte asnType = ParseHeader(buffer, ref offset, out headerLength);
60 |
61 | /* Ignore type. This should be set in the inherited class. */
62 | if (asnType != Type)
63 | throw new SnmpException("Invalid ASN.1 type");
64 |
65 | if (headerLength != 0)
66 | throw new SnmpException("Invalid ASN.1 length");
67 | return offset;
68 | }
69 |
70 | /// Returns a duplicate of the object.
71 | ///
72 | /// A new copy of the current object cast as System.Object.
73 | ///
74 | public override Object Clone()
75 | {
76 | return new V2Error(this);
77 | }
78 | }
79 | }
--------------------------------------------------------------------------------
/Types/V2PartyClock.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | namespace SnmpSharpNet
18 | {
19 |
20 | /// Defines an SNMPv2 Party Clock.
21 | ///
22 | /// The Party Clock is currently
23 | /// Obsolete, but included for backwards compatibility. Obsoleted in RFC 1902.
24 | ///
25 | public class V2PartyClock:UInteger32,ICloneable
26 | {
27 | /// Constructor
28 | public V2PartyClock():base()
29 | {
30 | _asnType = SnmpConstants.SMI_PARTY_CLOCK;
31 | }
32 |
33 | /// Constructor
34 | /// Class to duplicate
35 | public V2PartyClock(V2PartyClock second):base(second)
36 | {
37 | _asnType = SnmpConstants.SMI_PARTY_CLOCK;
38 | }
39 |
40 | /// Constructor
41 | /// Value to initialize the class with.
42 | public V2PartyClock(UInteger32 uint32):base(uint32)
43 | {
44 | _asnType = SnmpConstants.SMI_PARTY_CLOCK;
45 | }
46 |
47 | /// Clone class
48 | /// Cloned class cast as object
49 | public override System.Object Clone()
50 | {
51 | return new V2PartyClock(this);
52 | }
53 |
54 | /// Returns the string representation of the object.
55 | /// String representation of the class value.
56 | public override System.String ToString()
57 | {
58 | System.Text.StringBuilder buf = new System.Text.StringBuilder();
59 | long time = Value;
60 | long tmp = 0;
61 | if ((tmp = (time / (24 * 3600 * 100))) > 0)
62 | {
63 | buf.Append(tmp).Append("d ");
64 | time = time % (24 * 3600 * 100);
65 | }
66 | else
67 | buf.Append("0d ");
68 |
69 | if ((tmp = time / (3600 * 100)) > 0)
70 | {
71 | buf.Append(tmp).Append("h ");
72 | time = time % (3600 * 100);
73 | }
74 | else
75 | buf.Append("0h ");
76 |
77 | if ((tmp = time / 6000) > 0)
78 | {
79 | buf.Append(tmp).Append("m ");
80 | time = time % 6000;
81 | }
82 | else
83 | buf.Append("0m ");
84 |
85 | if ((tmp = time / 100) > 0)
86 | {
87 | buf.Append(tmp).Append("s ");
88 | time = time % 100;
89 | }
90 | else
91 | buf.Append("0s ");
92 |
93 | buf.Append(tmp * 10).Append("ms");
94 |
95 | return buf.ToString();
96 | }
97 | }
98 | }
--------------------------------------------------------------------------------
/Vb.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | using System.Collections.Generic;
18 | using System.Text;
19 | using System.Collections;
20 |
21 | namespace SnmpSharpNet {
22 | ///
23 | /// Vb item. Stores Oid => value pair for each value
24 | ///
25 | public class Vb : AsnType, ICloneable
26 | {
27 | ///
28 | /// OID of the object
29 | ///
30 | private Oid _oid;
31 | ///
32 | /// Value of the object
33 | ///
34 | private AsnType _value;
35 | ///
36 | /// Standard constructor. Initializes values to null.
37 | ///
38 | public Vb() {
39 | _asnType = (byte)(SEQUENCE | CONSTRUCTOR);
40 | }
41 | ///
42 | /// Construct Vb with the supplied OID and Null value
43 | ///
44 | /// OID
45 | public Vb(Oid oid)
46 | : this()
47 | {
48 | _oid = (Oid)oid.Clone();
49 | _value = new Null();
50 | }
51 | ///
52 | /// Construct Vb with the OID and value
53 | ///
54 | /// OID
55 | /// Value
56 | public Vb(Oid oid, AsnType value)
57 | : this(oid) {
58 | _value = (AsnType)value.Clone();
59 | }
60 | ///
61 | /// Construct Vb with the oid value and value.
62 | ///
63 | /// String representing OID value to set
64 | public Vb(string oid)
65 | : this()
66 | {
67 | _oid = new Oid(oid);
68 | _value = new Null();
69 | }
70 | ///
71 | /// Copy constructor. Initialize class with cloned values from second class.
72 | ///
73 | /// Vb class to clone data from.
74 | public Vb(Vb second)
75 | : this()
76 | {
77 | Set(second);
78 | }
79 | ///
80 | /// SET class value from supplied Vb class
81 | ///
82 | /// Vb class to clone data from
83 | public void Set(Vb value)
84 | {
85 | this._oid = (Oid)value.Oid.Clone();
86 | this._value = (Oid)value.Value.Clone();
87 | }
88 | ///
89 | /// SET/Get AsnType value of the Vb
90 | ///
91 | public AsnType Value {
92 | set {
93 | _value = (AsnType)value.Clone();
94 | }
95 | get {
96 | return _value;
97 | }
98 | }
99 | ///
100 | /// Get/SET OID of the Vb
101 | ///
102 | public Oid Oid {
103 | set {
104 | _oid = (Oid)value.Clone();
105 | }
106 | get {
107 | return _oid;
108 | }
109 | }
110 |
111 | ///
112 | /// Reset Vb value to Null
113 | ///
114 | public void ResetValue()
115 | {
116 | _value = new Null();
117 | }
118 |
119 | ///
120 | /// Clone Vb object
121 | ///
122 | /// Cloned Vb object cast to System.Object
123 | public override Object Clone() {
124 | return new Vb(this._oid, this._value);
125 | }
126 | ///
127 | /// Return printable string in the format oid: value
128 | ///
129 | /// Format Vb string
130 | public override string ToString() {
131 | return _oid.ToString() + ": (" + SnmpConstants.GetTypeName(_value.Type) + ") " + _value.ToString();
132 | }
133 | /// BER encode the variable binding
134 | ///
135 | /// class to the end of which encoded variable
136 | /// binding values will be added.
137 | ///
138 | public override void encode(MutableByte buffer)
139 | {
140 | // encode oid to the temporary buffer
141 | MutableByte oidbuf = new MutableByte();
142 | _oid.encode(oidbuf);
143 | // encode value to a temporary buffer
144 | MutableByte valbuf = new MutableByte();
145 | _value.encode(valbuf);
146 |
147 | // calculate data content length of the vb
148 | int vblen = oidbuf.Length + valbuf.Length;
149 | // encode vb header at the end of the result
150 | BuildHeader(buffer, Type, vblen);
151 | // add values to the encoded arrays to the end of the result
152 | buffer.Append(oidbuf);
153 | buffer.Append(valbuf);
154 | }
155 | /// Decode BER encoded variable binding.
156 | ///
157 | /// BER encoded buffer
158 | ///
159 | /// Offset in the data buffer from where to start decoding. Offset is
160 | /// passed by reference and will contain the offset of the byte immediately after the parsed
161 | /// variable binding.
162 | ///
163 | /// Buffer position after the decoded value
164 | public override int decode(byte[] buffer, int offset)
165 | {
166 | int headerLength;
167 | byte asnType = ParseHeader(buffer, ref offset, out headerLength);
168 |
169 | if (asnType != Type)
170 | throw new SnmpException(string.Format("Invalid ASN.1 type. Expected 0x{0:x2} received 0x{1:x2}", Type, asnType));
171 |
172 | // verify the length
173 | if ((buffer.Length - offset) < headerLength)
174 | throw new OverflowException("Buffer underflow error");
175 |
176 | _oid = new Oid();
177 | offset = _oid.decode(buffer, offset);
178 | int saveOffset = offset;
179 | // Look ahead in the header to see the data type we need to parse
180 | asnType = ParseHeader(buffer, ref saveOffset, out headerLength);
181 | _value = SnmpConstants.GetSyntaxObject(asnType);
182 | if (_value == null)
183 | throw new SnmpDecodingException(String.Format("Invalid ASN.1 type encountered 0x{0:x2}. Unable to continue decoding.", asnType));
184 | offset = _value.decode(buffer, offset);
185 | return offset;
186 | }
187 | }
188 | }
189 |
--------------------------------------------------------------------------------
/keypair.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rqx110/SnmpSharpNet/9ed0aed20ce2d6d1e39e00c7ac14d613bb697f0d/keypair.snk
--------------------------------------------------------------------------------
/public.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rqx110/SnmpSharpNet/9ed0aed20ce2d6d1e39e00c7ac14d613bb697f0d/public.snk
--------------------------------------------------------------------------------
/security/Authentication.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | /// Authentication helper class
20 | ///
21 | /// Helper class to make dealing with multiple (if 2 qualifies as multiple) authentication protocols in a
22 | /// transparent way.
23 | ///
24 | /// Calling class keeps the authentication protocol selection (as defined on the agent) in an integer
25 | /// variable that can have 3 values: , , or
26 | /// . Using , calling method can
27 | /// get authentication protocol implementation class instance cast as interface
28 | /// and perform authentication operations (either authenticate outgoing packets to verify authentication of incoming packets)
29 | /// without needing to further care about which authentication protocol is used.
30 | ///
31 | /// Example of how to use this class:
32 | ///
33 | /// IAuthenticationDigest authenticationImplementation = Authentication.GetInstance(AuthenticationDigests.MD5);
34 | /// authenticationImplementation.authenticateIncomingMsg(...);
35 | /// authenticationImplementation.authenticateOutgoingMsg(...);
36 | ///
37 | ///
38 | public sealed class Authentication
39 | {
40 |
41 | ///
42 | /// Get instance of authentication protocol.
43 | ///
44 | /// Authentication protocol code. Available codes are ,
45 | /// or
46 | /// Instance of the authentication protocol or null if unrecognized authentication protocol or value
47 | /// is passed.
48 | public static IAuthenticationDigest GetInstance(AuthenticationDigests authProtocol)
49 | {
50 | if (authProtocol == AuthenticationDigests.MD5)
51 | return new AuthenticationMD5();
52 | else if (authProtocol == AuthenticationDigests.SHA1)
53 | return new AuthenticationSHA1();
54 | else if (authProtocol == AuthenticationDigests.SHA256)
55 | return new AuthenticationSHA256();
56 | else if (authProtocol == AuthenticationDigests.SHA384)
57 | return new AuthenticationSHA384();
58 | else if (authProtocol == AuthenticationDigests.SHA512)
59 | return new AuthenticationSHA512();
60 | return null;
61 | }
62 | ///
63 | /// Constructor. Private to prevent the class from being instantiated.
64 | ///
65 | private Authentication()
66 | {
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/security/AuthenticationDigests.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Enumeration of available authentication digests
21 | ///
22 | public enum AuthenticationDigests
23 | {
24 | ///
25 | /// Authentication hash method none. Used when authentication is disabled.
26 | ///
27 | None = 0,
28 | ///
29 | /// Authentication protocol is HMAC-MD5.
30 | ///
31 | MD5,
32 | ///
33 | /// Authentication protocol is HMAC-SHA1.
34 | ///
35 | SHA1,
36 | ///
37 | /// Authentication protocol is HMAC-SHA256.
38 | ///
39 | SHA256,
40 | ///
41 | /// Authentication protocol is HMAC-SHA384.
42 | ///
43 | SHA384,
44 | ///
45 | /// Authentication protocol is HMAC-SHA512.
46 | ///
47 | SHA512
48 |
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/security/AuthenticationMD5.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | using System.Security.Cryptography;
18 |
19 | namespace SnmpSharpNet
20 | {
21 | ///
22 | /// MD5 Authentication class.
23 | ///
24 | public class AuthenticationMD5: IAuthenticationDigest
25 | {
26 | private const int authenticationLength = 12;
27 | private const int digestLength = 16;
28 |
29 | ///
30 | /// Standard constructor
31 | ///
32 | public AuthenticationMD5()
33 | {
34 | }
35 |
36 | ///
37 | /// Authenticate packet and return authentication parameters value to the caller
38 | ///
39 | /// User authentication secret
40 | /// SNMP agent authoritative engine id
41 | /// Message to authenticate
42 | /// Authentication parameters value
43 | public byte[] authenticate(byte[] authenticationSecret, byte[] engineId, byte[] wholeMessage)
44 | {
45 | byte[] result = new byte[authenticationLength];
46 | byte[] authKey = PasswordToKey(authenticationSecret, engineId);
47 | HMACMD5 md5 = new HMACMD5(authKey);
48 | byte[] hash = md5.ComputeHash(wholeMessage);
49 | // copy "authentication lenght" bytes of the hash into the wholeMessage
50 | Buffer.BlockCopy(hash, 0, result, 0, authenticationLength);
51 | return result;
52 | }
53 |
54 | ///
55 | /// Authenticate packet and return authentication parameters value to the caller
56 | ///
57 | /// Pre-generated authentication key
58 | /// Message being authenticated
59 | /// Authentication parameters value
60 | public byte[] authenticate(byte[] authKey, byte[] wholeMessage)
61 | {
62 | byte[] result = new byte[authenticationLength];
63 | HMACMD5 md5 = new HMACMD5(authKey);
64 | byte[] hash = md5.ComputeHash(wholeMessage);
65 | // copy "authentication lenght" bytes of the hash into the wholeMessage
66 | Buffer.BlockCopy(hash, 0, result, 0, authenticationLength);
67 | return result;
68 | }
69 |
70 | ///
71 | /// Verifies correct MD5 authentication of the frame. Prior to calling this method, you have to extract authentication
72 | /// parameters from the wholeMessage and reset authenticationParameters field in the USM information block to 12 0x00
73 | /// values.
74 | ///
75 | /// User password
76 | /// Authoritative engine id
77 | /// Extracted USM authentication parameters
78 | /// Whole message with authentication parameters zeroed (0x00) out
79 | /// True if message authentication has passed the check, otherwise false
80 | public bool authenticateIncomingMsg(byte[] userPassword, byte[] engineId, byte[] authenticationParameters, MutableByte wholeMessage)
81 | {
82 | byte[] authKey = PasswordToKey(userPassword, engineId);
83 | HMACMD5 md5 = new HMACMD5(authKey);
84 | byte[] hash = md5.ComputeHash(wholeMessage, 0, wholeMessage.Length);
85 | MutableByte myhash = new MutableByte(hash, authenticationLength);
86 | if (myhash.Equals(authenticationParameters))
87 | {
88 | return true;
89 | }
90 | return false;
91 | }
92 | ///
93 | /// Verify MD5 authentication of a packet.
94 | ///
95 | /// Authentication key (not password)
96 | /// Authentication parameters extracted from the packet being authenticated
97 | /// Entire packet being authenticated
98 | /// True on authentication success, otherwise false
99 | public bool authenticateIncomingMsg(byte[] authKey, byte[] authenticationParameters, MutableByte wholeMessage)
100 | {
101 | HMACMD5 md5 = new HMACMD5(authKey);
102 | byte[] hash = md5.ComputeHash(wholeMessage, 0, wholeMessage.Length);
103 | MutableByte myhash = new MutableByte(hash, authenticationLength);
104 | if (myhash.Equals(authenticationParameters))
105 | {
106 | return true;
107 | }
108 | return false;
109 | }
110 | ///
111 | /// Convert user password to acceptable authentication key.
112 | ///
113 | /// Authentication password
114 | /// Authoritative engine id
115 | /// Localized authentication key
116 | /// Thrown when key length is less then 8 bytes
117 | public byte[] PasswordToKey(byte[] userPassword, byte[] engineID)
118 | {
119 | // key length has to be at least 8 bytes long (RFC3414)
120 | if (userPassword == null || userPassword.Length < 8)
121 | throw new SnmpAuthenticationException("Secret key is too short.");
122 |
123 | int password_index = 0;
124 | int count = 0;
125 | MD5 md5 = new MD5CryptoServiceProvider();
126 |
127 | byte[] sourceBuffer = new byte[1048576];
128 | byte[] buf = new byte[64];
129 | while (count < 1048576)
130 | {
131 | for (int i = 0; i < 64; ++i)
132 | {
133 | buf[i] = userPassword[password_index++ % userPassword.Length];
134 | }
135 | Buffer.BlockCopy(buf, 0, sourceBuffer, count, buf.Length);
136 | count += 64;
137 | }
138 |
139 | byte[] digest = md5.ComputeHash(sourceBuffer);
140 |
141 | MutableByte tmpbuf = new MutableByte();
142 | tmpbuf.Append(digest);
143 | tmpbuf.Append(engineID);
144 | tmpbuf.Append(digest);
145 | byte[] key = md5.ComputeHash(tmpbuf);
146 |
147 | return key;
148 | }
149 |
150 | ///
151 | /// Length of the digest generated by the authentication protocol
152 | ///
153 | public int DigestLength
154 | {
155 | get { return digestLength; }
156 | }
157 |
158 | ///
159 | /// Length of the authentification header generated by the authentication protocol
160 | ///
161 | public int AuthentificationHeaderLength
162 | {
163 | get { return authenticationLength; }
164 | }
165 |
166 | ///
167 | /// Return protocol name.
168 | ///
169 | public string Name
170 | {
171 | get { return "HMAC-MD5"; }
172 | }
173 | ///
174 | /// Compute hash using authentication protocol.
175 | ///
176 | /// Data to hash
177 | /// Compute hash from the source buffer offset
178 | /// Compute hash for source data length
179 | /// Hash value
180 | public byte[] ComputeHash(byte[] data, int offset, int count)
181 | {
182 | MD5 md5 = new MD5CryptoServiceProvider();
183 | byte[] res = md5.ComputeHash(data, offset, count);
184 | md5.Clear();
185 | return res;
186 | }
187 | }
188 | }
189 |
--------------------------------------------------------------------------------
/security/AuthenticationSHA1.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | using System.Security.Cryptography;
18 |
19 | namespace SnmpSharpNet
20 | {
21 | ///
22 | /// SHA-1 Authentication class.
23 | ///
24 | public class AuthenticationSHA1 : IAuthenticationDigest
25 | {
26 | private const int authenticationLength = 12;
27 | private const int digestLength = 20;
28 |
29 | ///
30 | /// Standard constructor.
31 | ///
32 | public AuthenticationSHA1()
33 | {
34 | }
35 | ///
36 | /// Authenticate packet and return authentication parameters value to the caller
37 | ///
38 | /// User authentication secret
39 | /// SNMP agent authoritative engine id
40 | /// Message to authenticate
41 | /// Authentication parameters value
42 | public byte[] authenticate(byte[] authenticationSecret, byte[] engineId, byte[] wholeMessage)
43 | {
44 | byte[] result = new byte[authenticationLength];
45 | byte[] authKey = PasswordToKey(authenticationSecret, engineId);
46 | HMACSHA1 sha = new HMACSHA1(authKey);
47 | byte[] hash = sha.ComputeHash(wholeMessage);
48 | // copy "authentication lenght" bytes of the hash into the wholeMessage
49 | for (int i = 0; i < authenticationLength; i++)
50 | {
51 | result[i] = hash[i];
52 | }
53 | sha.Clear(); // release resources
54 | return result;
55 | }
56 | ///
57 | /// Authenticate packet and return authentication parameters value to the caller
58 | ///
59 | /// Authentication key (not password)
60 | /// Message to authenticate
61 | /// Authentication parameters value
62 | public byte[] authenticate(byte[] authKey, byte[] wholeMessage)
63 | {
64 | byte[] result = new byte[authenticationLength];
65 |
66 | HMACSHA1 sha = new HMACSHA1(authKey);
67 | byte[] hash = sha.ComputeHash(wholeMessage);
68 | // copy "authentication lenght" bytes of the hash into the wholeMessage
69 | for (int i = 0; i < authenticationLength; i++)
70 | {
71 | result[i] = hash[i];
72 | }
73 | sha.Clear(); // release resources
74 | return result;
75 | }
76 | ///
77 | /// Verifies correct SHA-1 authentication of the frame. Prior to calling this method, you have to extract authentication
78 | /// parameters from the wholeMessage and reset authenticationParameters field in the USM information block to 12 0x00
79 | /// values.
80 | ///
81 | /// User password
82 | /// Authoritative engine id
83 | /// Extracted USM authentication parameters
84 | /// Whole message with authentication parameters zeroed (0x00) out
85 | /// True if message authentication has passed the check, otherwise false
86 | public bool authenticateIncomingMsg(byte[] userPassword, byte[] engineId, byte[] authenticationParameters, MutableByte wholeMessage)
87 | {
88 | byte[] authKey = PasswordToKey(userPassword, engineId);
89 | HMACSHA1 sha = new HMACSHA1(authKey);
90 | byte[] hash = sha.ComputeHash(wholeMessage);
91 | MutableByte myhash = new MutableByte(hash, authenticationLength);
92 | sha.Clear(); // release resources
93 | if (myhash.Equals(authenticationParameters))
94 | {
95 | return true;
96 | }
97 | return false;
98 | }
99 | ///
100 | /// Verify SHA-1 authentication of a packet.
101 | ///
102 | /// Authentication key (not password)
103 | /// Authentication parameters extracted from the packet being authenticated
104 | /// Entire packet being authenticated
105 | /// True on authentication success, otherwise false
106 | public bool authenticateIncomingMsg(byte[] authKey, byte[] authenticationParameters, MutableByte wholeMessage)
107 | {
108 | HMACSHA1 sha = new HMACSHA1(authKey);
109 | byte[] hash = sha.ComputeHash(wholeMessage);
110 | MutableByte myhash = new MutableByte(hash, authenticationLength);
111 | sha.Clear(); // release resources
112 | if (myhash.Equals(authenticationParameters))
113 | {
114 | return true;
115 | }
116 | return false;
117 | }
118 | ///
119 | /// Convert user password to acceptable authentication key.
120 | ///
121 | /// User password
122 | /// Authoritative engine id
123 | /// Localized authentication key
124 | /// Thrown when key length is less then 8 bytes
125 | public byte[] PasswordToKey(byte[] userPassword, byte[] engineID)
126 | {
127 | // key length has to be at least 8 bytes long (RFC3414)
128 | if (userPassword == null || userPassword.Length < 8)
129 | throw new SnmpAuthenticationException("Secret key is too short.");
130 |
131 | int password_index = 0;
132 | int count = 0;
133 | SHA1 sha = new SHA1CryptoServiceProvider();
134 |
135 | /* Use while loop until we've done 1 Megabyte */
136 | byte[] sourceBuffer = new byte[1048576];
137 | byte[] buf = new byte[64];
138 | while (count < 1048576)
139 | {
140 | for (int i = 0; i < 64; ++i)
141 | {
142 | // Take the next octet of the password, wrapping
143 | // to the beginning of the password as necessary.
144 | buf[i] = userPassword[password_index++ % userPassword.Length];
145 | }
146 | Buffer.BlockCopy(buf, 0, sourceBuffer, count, buf.Length);
147 | count += 64;
148 | }
149 |
150 | byte[] digest = sha.ComputeHash(sourceBuffer);
151 |
152 | MutableByte tmpbuf = new MutableByte();
153 | tmpbuf.Append(digest);
154 | tmpbuf.Append(engineID);
155 | tmpbuf.Append(digest);
156 | byte[] res = sha.ComputeHash(tmpbuf);
157 | sha.Clear(); // release resources
158 | return res;
159 | }
160 |
161 | ///
162 | /// Length of the digest generated by the authentication protocol
163 | ///
164 | public int DigestLength
165 | {
166 | get { return digestLength; }
167 | }
168 |
169 | ///
170 | /// Length of the authentification header generated by the authentication protocol
171 | ///
172 | public int AuthentificationHeaderLength
173 | {
174 | get { return authenticationLength; }
175 | }
176 |
177 | ///
178 | /// Return authentication protocol name
179 | ///
180 | public string Name
181 | {
182 | get { return "HMAC-SHA1"; }
183 | }
184 | ///
185 | /// Compute hash using authentication protocol.
186 | ///
187 | /// Data to hash
188 | /// Compute hash from the source buffer offset
189 | /// Compute hash for source data length
190 | /// Hash value
191 | public byte[] ComputeHash(byte[] data, int offset, int count)
192 | {
193 | SHA1 sha = new SHA1CryptoServiceProvider();
194 | byte[] res = sha.ComputeHash(data, offset, count);
195 | sha.Clear();
196 | return res;
197 | }
198 | }
199 | }
200 |
--------------------------------------------------------------------------------
/security/AuthenticationSHA256.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | using System.Security.Cryptography;
18 |
19 | namespace SnmpSharpNet
20 | {
21 | ///
22 | /// SHA-256 Authentication class.
23 | ///
24 | public class AuthenticationSHA256 : IAuthenticationDigest
25 | {
26 | private const int authenticationLength = 24;
27 | private const int digestLength = 32;
28 |
29 | ///
30 | /// Standard constructor.
31 | ///
32 | public AuthenticationSHA256()
33 | {
34 | }
35 | ///
36 | /// Authenticate packet and return authentication parameters value to the caller
37 | ///
38 | /// User authentication secret
39 | /// SNMP agent authoritative engine id
40 | /// Message to authenticate
41 | /// Authentication parameters value
42 | public byte[] authenticate(byte[] authenticationSecret, byte[] engineId, byte[] wholeMessage)
43 | {
44 | byte[] result = new byte[authenticationLength];
45 | byte[] authKey = PasswordToKey(authenticationSecret, engineId);
46 | HMACSHA256 sha = new HMACSHA256(authKey);
47 | byte[] hash = sha.ComputeHash(wholeMessage);
48 | // copy "authentication lenght" bytes of the hash into the wholeMessage
49 | for (int i = 0; i < authenticationLength; i++)
50 | {
51 | result[i] = hash[i];
52 | }
53 | sha.Clear(); // release resources
54 | return result;
55 | }
56 | ///
57 | /// Authenticate packet and return authentication parameters value to the caller
58 | ///
59 | /// Authentication key (not password)
60 | /// Message to authenticate
61 | /// Authentication parameters value
62 | public byte[] authenticate(byte[] authKey, byte[] wholeMessage)
63 | {
64 | byte[] result = new byte[authenticationLength];
65 |
66 | HMACSHA256 sha = new HMACSHA256(authKey);
67 | byte[] hash = sha.ComputeHash(wholeMessage);
68 | // copy "authentication lenght" bytes of the hash into the wholeMessage
69 | for (int i = 0; i < authenticationLength; i++)
70 | {
71 | result[i] = hash[i];
72 | }
73 | sha.Clear(); // release resources
74 | return result;
75 | }
76 | ///
77 | /// Verifies correct SHA-256 authentication of the frame. Prior to calling this method, you have to extract authentication
78 | /// parameters from the wholeMessage and reset authenticationParameters field in the USM information block to 12 0x00
79 | /// values.
80 | ///
81 | /// User password
82 | /// Authoritative engine id
83 | /// Extracted USM authentication parameters
84 | /// Whole message with authentication parameters zeroed (0x00) out
85 | /// True if message authentication has passed the check, otherwise false
86 | public bool authenticateIncomingMsg(byte[] userPassword, byte[] engineId, byte[] authenticationParameters, MutableByte wholeMessage)
87 | {
88 | byte[] authKey = PasswordToKey(userPassword, engineId);
89 | HMACSHA256 sha = new HMACSHA256(authKey);
90 | byte[] hash = sha.ComputeHash(wholeMessage);
91 | MutableByte myhash = new MutableByte(hash, authenticationLength);
92 | sha.Clear(); // release resources
93 | if (myhash.Equals(authenticationParameters))
94 | {
95 | return true;
96 | }
97 | return false;
98 | }
99 | ///
100 | /// Verify SHA-256 authentication of a packet.
101 | ///
102 | /// Authentication key (not password)
103 | /// Authentication parameters extracted from the packet being authenticated
104 | /// Entire packet being authenticated
105 | /// True on authentication success, otherwise false
106 | public bool authenticateIncomingMsg(byte[] authKey, byte[] authenticationParameters, MutableByte wholeMessage)
107 | {
108 | HMACSHA256 sha = new HMACSHA256(authKey);
109 | byte[] hash = sha.ComputeHash(wholeMessage);
110 | MutableByte myhash = new MutableByte(hash, authenticationLength);
111 | sha.Clear(); // release resources
112 | if (myhash.Equals(authenticationParameters))
113 | {
114 | return true;
115 | }
116 | return false;
117 | }
118 | ///
119 | /// Convert user password to acceptable authentication key.
120 | ///
121 | /// User password
122 | /// Authoritative engine id
123 | /// Localized authentication key
124 | /// Thrown when key length is less then 8 bytes
125 | public byte[] PasswordToKey(byte[] userPassword, byte[] engineID)
126 | {
127 | // key length has to be at least 8 bytes long (RFC3414)
128 | if (userPassword == null || userPassword.Length < 8)
129 | throw new SnmpAuthenticationException("Secret key is too short.");
130 |
131 | int password_index = 0;
132 | int count = 0;
133 | SHA256 sha = new SHA256CryptoServiceProvider();
134 |
135 | /* Use while loop until we've done 1 Megabyte */
136 | byte[] sourceBuffer = new byte[1048576];
137 | byte[] buf = new byte[64];
138 | while (count < 1048576)
139 | {
140 | for (int i = 0; i < 64; ++i)
141 | {
142 | // Take the next octet of the password, wrapping
143 | // to the beginning of the password as necessary.
144 | buf[i] = userPassword[password_index++ % userPassword.Length];
145 | }
146 | Buffer.BlockCopy(buf, 0, sourceBuffer, count, buf.Length);
147 | count += 64;
148 | }
149 |
150 | byte[] digest = sha.ComputeHash(sourceBuffer);
151 |
152 | MutableByte tmpbuf = new MutableByte();
153 | tmpbuf.Append(digest);
154 | tmpbuf.Append(engineID);
155 | tmpbuf.Append(digest);
156 | byte[] res = sha.ComputeHash(tmpbuf);
157 | sha.Clear(); // release resources
158 | return res;
159 | }
160 |
161 | ///
162 | /// Length of the digest generated by the authentication protocol
163 | ///
164 | public int DigestLength
165 | {
166 | get { return digestLength; }
167 | }
168 |
169 | ///
170 | /// Length of the authentification header generated by the authentication protocol
171 | ///
172 | public int AuthentificationHeaderLength
173 | {
174 | get { return authenticationLength; }
175 | }
176 |
177 | ///
178 | /// Return authentication protocol name
179 | ///
180 | public string Name
181 | {
182 | get { return "HMAC-SHA256"; }
183 | }
184 | ///
185 | /// Compute hash using authentication protocol.
186 | ///
187 | /// Data to hash
188 | /// Compute hash from the source buffer offset
189 | /// Compute hash for source data length
190 | /// Hash value
191 | public byte[] ComputeHash(byte[] data, int offset, int count)
192 | {
193 | SHA256 sha = new SHA256CryptoServiceProvider();
194 | byte[] res = sha.ComputeHash(data, offset, count);
195 | sha.Clear();
196 | return res;
197 | }
198 | }
199 | }
200 |
--------------------------------------------------------------------------------
/security/AuthenticationSHA384.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | using System.Security.Cryptography;
18 |
19 | namespace SnmpSharpNet
20 | {
21 | ///
22 | /// SHA-384 Authentication class.
23 | ///
24 | public class AuthenticationSHA384 : IAuthenticationDigest
25 | {
26 | private const int authenticationLength = 32;
27 | private const int digestLength = 48;
28 |
29 | ///
30 | /// Standard constructor.
31 | ///
32 | public AuthenticationSHA384()
33 | {
34 | }
35 | ///
36 | /// Authenticate packet and return authentication parameters value to the caller
37 | ///
38 | /// User authentication secret
39 | /// SNMP agent authoritative engine id
40 | /// Message to authenticate
41 | /// Authentication parameters value
42 | public byte[] authenticate(byte[] authenticationSecret, byte[] engineId, byte[] wholeMessage)
43 | {
44 | byte[] result = new byte[authenticationLength];
45 | byte[] authKey = PasswordToKey(authenticationSecret, engineId);
46 | HMACSHA384 sha = new HMACSHA384(authKey);
47 | byte[] hash = sha.ComputeHash(wholeMessage);
48 | // copy "authentication lenght" bytes of the hash into the wholeMessage
49 | for (int i = 0; i < authenticationLength; i++)
50 | {
51 | result[i] = hash[i];
52 | }
53 | sha.Clear(); // release resources
54 | return result;
55 | }
56 | ///
57 | /// Authenticate packet and return authentication parameters value to the caller
58 | ///
59 | /// Authentication key (not password)
60 | /// Message to authenticate
61 | /// Authentication parameters value
62 | public byte[] authenticate(byte[] authKey, byte[] wholeMessage)
63 | {
64 | byte[] result = new byte[authenticationLength];
65 |
66 | HMACSHA384 sha = new HMACSHA384(authKey);
67 | byte[] hash = sha.ComputeHash(wholeMessage);
68 | // copy "authentication lenght" bytes of the hash into the wholeMessage
69 | for (int i = 0; i < authenticationLength; i++)
70 | {
71 | result[i] = hash[i];
72 | }
73 | sha.Clear(); // release resources
74 | return result;
75 | }
76 | ///
77 | /// Verifies correct SHA-384 authentication of the frame. Prior to calling this method, you have to extract authentication
78 | /// parameters from the wholeMessage and reset authenticationParameters field in the USM information block to 12 0x00
79 | /// values.
80 | ///
81 | /// User password
82 | /// Authoritative engine id
83 | /// Extracted USM authentication parameters
84 | /// Whole message with authentication parameters zeroed (0x00) out
85 | /// True if message authentication has passed the check, otherwise false
86 | public bool authenticateIncomingMsg(byte[] userPassword, byte[] engineId, byte[] authenticationParameters, MutableByte wholeMessage)
87 | {
88 | byte[] authKey = PasswordToKey(userPassword, engineId);
89 | HMACSHA384 sha = new HMACSHA384(authKey);
90 | byte[] hash = sha.ComputeHash(wholeMessage);
91 | MutableByte myhash = new MutableByte(hash, authenticationLength);
92 | sha.Clear(); // release resources
93 | if (myhash.Equals(authenticationParameters))
94 | {
95 | return true;
96 | }
97 | return false;
98 | }
99 | ///
100 | /// Verify SHA-384 authentication of a packet.
101 | ///
102 | /// Authentication key (not password)
103 | /// Authentication parameters extracted from the packet being authenticated
104 | /// Entire packet being authenticated
105 | /// True on authentication success, otherwise false
106 | public bool authenticateIncomingMsg(byte[] authKey, byte[] authenticationParameters, MutableByte wholeMessage)
107 | {
108 | HMACSHA384 sha = new HMACSHA384(authKey);
109 | byte[] hash = sha.ComputeHash(wholeMessage);
110 | MutableByte myhash = new MutableByte(hash, authenticationLength);
111 | sha.Clear(); // release resources
112 | if (myhash.Equals(authenticationParameters))
113 | {
114 | return true;
115 | }
116 | return false;
117 | }
118 | ///
119 | /// Convert user password to acceptable authentication key.
120 | ///
121 | /// User password
122 | /// Authoritative engine id
123 | /// Localized authentication key
124 | /// Thrown when key length is less then 8 bytes
125 | public byte[] PasswordToKey(byte[] userPassword, byte[] engineID)
126 | {
127 | // key length has to be at least 8 bytes long (RFC3414)
128 | if (userPassword == null || userPassword.Length < 8)
129 | throw new SnmpAuthenticationException("Secret key is too short.");
130 |
131 | int password_index = 0;
132 | int count = 0;
133 | SHA384 sha = new SHA384CryptoServiceProvider();
134 |
135 | /* Use while loop until we've done 1 Megabyte */
136 | byte[] sourceBuffer = new byte[1048576];
137 | byte[] buf = new byte[64];
138 | while (count < 1048576)
139 | {
140 | for (int i = 0; i < 64; ++i)
141 | {
142 | // Take the next octet of the password, wrapping
143 | // to the beginning of the password as necessary.
144 | buf[i] = userPassword[password_index++ % userPassword.Length];
145 | }
146 | Buffer.BlockCopy(buf, 0, sourceBuffer, count, buf.Length);
147 | count += 64;
148 | }
149 |
150 | byte[] digest = sha.ComputeHash(sourceBuffer);
151 |
152 | MutableByte tmpbuf = new MutableByte();
153 | tmpbuf.Append(digest);
154 | tmpbuf.Append(engineID);
155 | tmpbuf.Append(digest);
156 | byte[] res = sha.ComputeHash(tmpbuf);
157 | sha.Clear(); // release resources
158 | return res;
159 | }
160 |
161 | ///
162 | /// Length of the digest generated by the authentication protocol
163 | ///
164 | public int DigestLength
165 | {
166 | get { return digestLength; }
167 | }
168 |
169 | ///
170 | /// Length of the authentification header generated by the authentication protocol
171 | ///
172 | public int AuthentificationHeaderLength
173 | {
174 | get { return authenticationLength; }
175 | }
176 |
177 | ///
178 | /// Return authentication protocol name
179 | ///
180 | public string Name
181 | {
182 | get { return "HMAC-SHA384"; }
183 | }
184 | ///
185 | /// Compute hash using authentication protocol.
186 | ///
187 | /// Data to hash
188 | /// Compute hash from the source buffer offset
189 | /// Compute hash for source data length
190 | /// Hash value
191 | public byte[] ComputeHash(byte[] data, int offset, int count)
192 | {
193 | SHA384 sha = new SHA384CryptoServiceProvider();
194 | byte[] res = sha.ComputeHash(data, offset, count);
195 | sha.Clear();
196 | return res;
197 | }
198 | }
199 | }
200 |
--------------------------------------------------------------------------------
/security/AuthenticationSHA512.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | using System.Security.Cryptography;
18 |
19 | namespace SnmpSharpNet
20 | {
21 | ///
22 | /// SHA-512 Authentication class.
23 | ///
24 | public class AuthenticationSHA512 : IAuthenticationDigest
25 | {
26 | private const int authenticationLength = 48;
27 | private const int digestLength = 64;
28 | ///
29 | /// Standard constructor.
30 | ///
31 | public AuthenticationSHA512()
32 | {
33 | }
34 | ///
35 | /// Authenticate packet and return authentication parameters value to the caller
36 | ///
37 | /// User authentication secret
38 | /// SNMP agent authoritative engine id
39 | /// Message to authenticate
40 | /// Authentication parameters value
41 | public byte[] authenticate(byte[] authenticationSecret, byte[] engineId, byte[] wholeMessage)
42 | {
43 | byte[] result = new byte[authenticationLength];
44 | byte[] authKey = PasswordToKey(authenticationSecret, engineId);
45 | HMACSHA512 sha = new HMACSHA512(authKey);
46 | byte[] hash = sha.ComputeHash(wholeMessage);
47 | // copy "authentication lenght" bytes of the hash into the wholeMessage
48 | for (int i = 0; i < authenticationLength; i++)
49 | {
50 | result[i] = hash[i];
51 | }
52 | sha.Clear(); // release resources
53 | return result;
54 | }
55 | ///
56 | /// Authenticate packet and return authentication parameters value to the caller
57 | ///
58 | /// Authentication key (not password)
59 | /// Message to authenticate
60 | /// Authentication parameters value
61 | public byte[] authenticate(byte[] authKey, byte[] wholeMessage)
62 | {
63 | byte[] result = new byte[authenticationLength];
64 |
65 | HMACSHA512 sha = new HMACSHA512(authKey);
66 | byte[] hash = sha.ComputeHash(wholeMessage);
67 | // copy "authentication lenght" bytes of the hash into the wholeMessage
68 | for (int i = 0; i < authenticationLength; i++)
69 | {
70 | result[i] = hash[i];
71 | }
72 | sha.Clear(); // release resources
73 | return result;
74 | }
75 | ///
76 | /// Verifies correct SHA-512 authentication of the frame. Prior to calling this method, you have to extract authentication
77 | /// parameters from the wholeMessage and reset authenticationParameters field in the USM information block to 12 0x00
78 | /// values.
79 | ///
80 | /// User password
81 | /// Authoritative engine id
82 | /// Extracted USM authentication parameters
83 | /// Whole message with authentication parameters zeroed (0x00) out
84 | /// True if message authentication has passed the check, otherwise false
85 | public bool authenticateIncomingMsg(byte[] userPassword, byte[] engineId, byte[] authenticationParameters, MutableByte wholeMessage)
86 | {
87 | byte[] authKey = PasswordToKey(userPassword, engineId);
88 | HMACSHA512 sha = new HMACSHA512(authKey);
89 | byte[] hash = sha.ComputeHash(wholeMessage);
90 | MutableByte myhash = new MutableByte(hash, authenticationLength);
91 | sha.Clear(); // release resources
92 | if (myhash.Equals(authenticationParameters))
93 | {
94 | return true;
95 | }
96 | return false;
97 | }
98 | ///
99 | /// Verify SHA-512 authentication of a packet.
100 | ///
101 | /// Authentication key (not password)
102 | /// Authentication parameters extracted from the packet being authenticated
103 | /// Entire packet being authenticated
104 | /// True on authentication success, otherwise false
105 | public bool authenticateIncomingMsg(byte[] authKey, byte[] authenticationParameters, MutableByte wholeMessage)
106 | {
107 | HMACSHA512 sha = new HMACSHA512(authKey);
108 | byte[] hash = sha.ComputeHash(wholeMessage);
109 | MutableByte myhash = new MutableByte(hash, authenticationLength);
110 | sha.Clear(); // release resources
111 | if (myhash.Equals(authenticationParameters))
112 | {
113 | return true;
114 | }
115 | return false;
116 | }
117 | ///
118 | /// Convert user password to acceptable authentication key.
119 | ///
120 | /// User password
121 | /// Authoritative engine id
122 | /// Localized authentication key
123 | /// Thrown when key length is less then 8 bytes
124 | public byte[] PasswordToKey(byte[] userPassword, byte[] engineID)
125 | {
126 | // key length has to be at least 8 bytes long (RFC3414)
127 | if (userPassword == null || userPassword.Length < 8)
128 | throw new SnmpAuthenticationException("Secret key is too short.");
129 |
130 | int password_index = 0;
131 | int count = 0;
132 | SHA512 sha = new SHA512CryptoServiceProvider();
133 |
134 | /* Use while loop until we've done 1 Megabyte */
135 | byte[] sourceBuffer = new byte[1048576];
136 | byte[] buf = new byte[64];
137 | while (count < 1048576)
138 | {
139 | for (int i = 0; i < 64; ++i)
140 | {
141 | // Take the next octet of the password, wrapping
142 | // to the beginning of the password as necessary.
143 | buf[i] = userPassword[password_index++ % userPassword.Length];
144 | }
145 | Buffer.BlockCopy(buf, 0, sourceBuffer, count, buf.Length);
146 | count += 64;
147 | }
148 |
149 | byte[] digest = sha.ComputeHash(sourceBuffer);
150 |
151 | MutableByte tmpbuf = new MutableByte();
152 | tmpbuf.Append(digest);
153 | tmpbuf.Append(engineID);
154 | tmpbuf.Append(digest);
155 | byte[] res = sha.ComputeHash(tmpbuf);
156 | sha.Clear(); // release resources
157 | return res;
158 | }
159 |
160 | ///
161 | /// Length of the digest generated by the authentication protocol
162 | ///
163 | public int DigestLength
164 | {
165 | get { return digestLength; }
166 | }
167 |
168 | ///
169 | /// Length of the authentification header generated by the authentication protocol
170 | ///
171 | public int AuthentificationHeaderLength
172 | {
173 | get { return authenticationLength; }
174 | }
175 |
176 | ///
177 | /// Return authentication protocol name
178 | ///
179 | public string Name
180 | {
181 | get { return "HMAC-SHA512"; }
182 | }
183 | ///
184 | /// Compute hash using authentication protocol.
185 | ///
186 | /// Data to hash
187 | /// Compute hash from the source buffer offset
188 | /// Compute hash for source data length
189 | /// Hash value
190 | public byte[] ComputeHash(byte[] data, int offset, int count)
191 | {
192 | SHA512 sha = new SHA512CryptoServiceProvider();
193 | byte[] res = sha.ComputeHash(data, offset, count);
194 | sha.Clear();
195 | return res;
196 | }
197 | }
198 | }
199 |
--------------------------------------------------------------------------------
/security/IAuthenticationDigest.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Authentication digest interface. Interface defines authentication methods
21 | /// for incoming and outgoing requests.
22 | ///
23 | public interface IAuthenticationDigest
24 | {
25 | ///
26 | /// Authentication outgoing message
27 | ///
28 | /// Authentication secret
29 | /// SNMP version 3 agent engine id
30 | /// Message to authenticate
31 | /// Authentication parameters
32 | byte[] authenticate(byte[] userPassword, byte[] engineId, byte[] wholeMessage);
33 |
34 | ///
35 | /// Authentication outgoing message
36 | ///
37 | /// Authentication key
38 | /// Message to authenticate
39 | /// Authentication parameters
40 | byte[] authenticate(byte[] authKey, byte[] wholeMessage);
41 |
42 | ///
43 | /// Returns the size of the native algorithm. This value does not represent the size of the digest
44 | /// that is stored inside the USM authentication parameters header but real length generated by it.
45 | ///
46 | int DigestLength
47 | {
48 | get;
49 | }
50 |
51 | ///
52 | /// Returns the size of the authentification header length. This value represent the size of the digest
53 | /// that is stored inside the USM authentication parameters header.
54 | ///
55 | int AuthentificationHeaderLength
56 | {
57 | get;
58 | }
59 |
60 | ///
61 | /// Authenticate incoming messages
62 | ///
63 | /// Authentication user secret (password)
64 | /// SNMP agent authoritative engine id
65 | /// Authentication parameters from the incoming packet
66 | /// Entire message with authentication parameters field zeroed out
67 | /// True if packet is authenticated, otherwise false.
68 | bool authenticateIncomingMsg(byte[] authentiationSecret, byte[] engineId, byte[] authenticationParameters, MutableByte wholeMessage);
69 |
70 | ///
71 | /// Authenticate incoming messages
72 | ///
73 | /// Authentication key
74 | /// Authentication parameters from the incoming packet
75 | /// Entire message with authentication parameters field zeroed out
76 | /// True if packet is authenticated, otherwise false.
77 | bool authenticateIncomingMsg(byte[] authKey, byte[] authenticationParameters, MutableByte wholeMessage);
78 |
79 | ///
80 | /// Convert password to a key
81 | ///
82 | /// Authentication key
83 | /// Authoritative engine id
84 | /// Key value
85 | byte[] PasswordToKey(byte[] passwordString, byte[] engineID);
86 |
87 | ///
88 | /// Compute hash using authentication protocol.
89 | ///
90 | /// Data to hash
91 | /// Compute hash from the source buffer offset
92 | /// Compute hash for source data length
93 | /// Hash value
94 | byte[] ComputeHash(byte[] data, int offset, int count);
95 |
96 | ///
97 | /// Return authentication protocol name.
98 | ///
99 | string Name
100 | {
101 | get;
102 | }
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/security/IPrivacyProtocol.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Privacy protocol interface.
21 | ///
22 | ///
23 | /// Defines encryption and decryption methods for all privacy protocols allowing for any of the
24 | /// available protocols to be cast as the interface and called to perform privacy operations on packets.
25 | ///
26 | public interface IPrivacyProtocol
27 | {
28 | ///
29 | /// Encrypt data BER encoded in a byte array.
30 | ///
31 | /// BER encoded byte array that needs to be encrypted
32 | /// Offset within the BER encoded byte array to start encryption operation from.
33 | /// Length of data to encrypt
34 | /// Encryption key
35 | /// Authoritative engine boots value. Retrieved as part of SNMP v3 discovery process.
36 | /// Authoritative engine time value. Retrieved as part of SNMP v3 discovery process.
37 | /// Byte array that will receive privacy parameters information that is the result of the
38 | /// encryption procedure.
39 | /// Authentication digest class reference. Only needed for TripleDES privacy protocol. Can be null for all other
40 | /// privacy protocols.
41 | /// Byte array containing encrypted BER encoded data
42 | byte[] Encrypt(byte[] unencryptedData, int offset, int length, byte[] encryptionKey, int engineBoots, int engineTime, out byte[] privacyParameters, IAuthenticationDigest authDigest);
43 | ///
44 | /// Decrypt BER encoded byte array.
45 | ///
46 | /// Encrypted data byte array
47 | /// Offset within the buffer to start decryption process from
48 | /// Length of data to decrypt
49 | /// Decryption key
50 | /// Authoritative engine boots value. Retrieved as part of SNMP v3 discovery procedure
51 | /// Authoritative engine time value. Retrieved as part of SNMP v3 discovery procedure
52 | /// Privacy parameters parsed from the incoming packet.
53 | /// Byte array containing decrypted in BER encoded format.
54 | byte[] Decrypt(byte[] cryptedData, int offset, int length, byte[] key, int engineBoots, int engineTime, byte[] privacyParameters);
55 | ///
56 | /// Get minimum acceptable encryption/decryption key length for the protocol.
57 | ///
58 | int MinimumKeyLength
59 | {
60 | get;
61 | }
62 | ///
63 | /// Get maximum acceptable encryption/decryption key length for the protocol.
64 | ///
65 | int MaximumKeyLength
66 | {
67 | get;
68 | }
69 | /// SNMP version 3 packet privacy parameters field size
70 | ///
71 | /// Get length of the privacy parameters byte array that is generated by the encryption method and used by the
72 | /// decryption method.
73 | ///
74 | int PrivacyParametersLength
75 | {
76 | get;
77 | }
78 | ///
79 | /// Privacy protocol name
80 | ///
81 | string Name
82 | {
83 | get;
84 | }
85 | ///
86 | /// Calculates and returns length of the buffer that is the result of the encryption method.
87 | ///
88 | /// Length of the buffer that is needs to be encrypted.
89 | /// Length of the encrypted byte array after the call to Encrypt method.
90 | int GetEncryptedLength(int scopedPduLength);
91 | /// Extend short encryption key
92 | ///
93 | /// Some privacy protocols require generated key to be extended to match the minimum key size
94 | /// required by the encryption alghoritm. Where required, this method should be called by the
95 | /// inheriting class as part of PasswordToKey() method call without the need for user to call it.
96 | ///
97 | /// Key that needs to be extended
98 | /// Privacy password as configured on the SNMP agent.
99 | /// Authoritative engine id. Value is retrieved as part of SNMP v3 discovery procedure
100 | /// Authentication protocol class instance cast as
101 | /// Extended key value
102 | byte[] ExtendShortKey(byte[] shortKey, byte[] password, byte[] engineID, IAuthenticationDigest authProtocol);
103 |
104 | ///
105 | /// Returns true if derived class supports key extension, otherwise false.
106 | ///
107 | bool CanExtendShortKey
108 | {
109 | get;
110 | }
111 | ///
112 | /// Convert privacy password into encryption key using packet authentication hash.
113 | ///
114 | /// Privacy user secret
115 | /// Authoritative engine id of the snmp agent
116 | /// Authentication protocol
117 | /// Encryption key
118 | /// Thrown when key size is shorter then MinimumKeyLength
119 | byte[] PasswordToKey(byte[] secret, byte[] engineId, IAuthenticationDigest authProtocol);
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/security/MsgFlags.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 |
18 | namespace SnmpSharpNet
19 | {
20 | ///
21 | /// Message flags in the SNMP v3 header.
22 | ///
23 | ///
24 | /// Message flags hold flags that
25 | /// indicate if packet is authenticated, privacy protected and if
26 | /// report reply is expected on errors.
27 | ///
28 | /// Message flags field is a 1 byte encoded
29 | /// field.
30 | ///
31 | public class MsgFlags : AsnType, ICloneable
32 | {
33 | ///
34 | /// Bit value that, when set, indicates that packet has been authenticated.
35 | ///
36 | public static byte FLAG_AUTH = 0x01;
37 |
38 | ///
39 | /// Bit value that, when set, indicates that packet has been privacy protected.
40 | ///
41 | public static byte FLAG_PRIV = 0x02;
42 |
43 | ///
44 | /// Bit value that, when set, indicates that sender of the packet expects report packet to be sent by the agent on errors.
45 | ///
46 | public static byte FLAG_REPORTABLE = 0x04;
47 |
48 | ///
49 | /// True if authentication is used to secure the packet, otherwise false.
50 | ///
51 | protected bool _authenticationFlag;
52 | ///
53 | /// Get/Set authentication flag. Value is true if authentication is used, false if packet is not authenticated
54 | ///
55 | public bool Authentication
56 | {
57 | get { return _authenticationFlag; }
58 | set { _authenticationFlag = value; }
59 | }
60 | ///
61 | /// True if ScopedPdu portion of the packet is privacy protected with encryption, otherwise false.
62 | ///
63 | protected bool _privacyFlag;
64 | ///
65 | /// Get/Set privacy flag. Value is true if privacy protection is used, false if packet is not privacy protected.
66 | ///
67 | public bool Privacy
68 | {
69 | get { return _privacyFlag; }
70 | set { _privacyFlag = value; }
71 | }
72 | ///
73 | /// True if reportable flag is set, otherwise false.
74 | ///
75 | protected bool _reportableFlag;
76 | ///
77 | /// Get/Set reportable flag. Value is true if sender expects report packet on errors, false if sender does
78 | /// not expect report packets.
79 | ///
80 | public bool Reportable
81 | {
82 | get { return _reportableFlag; }
83 | set { _reportableFlag = value; }
84 | }
85 |
86 | ///
87 | /// Standard constructor. All flags are set to false by default.
88 | ///
89 | public MsgFlags()
90 | {
91 | _authenticationFlag = _privacyFlag = _reportableFlag = false;
92 | }
93 |
94 | ///
95 | /// Constructor. Initialize individual flag values.
96 | ///
97 | /// true if authentication is used, otherwise false
98 | /// true if privacy protection is used, otherwise false
99 | /// true if report is expected, otherwise false
100 | public MsgFlags(bool authentication, bool privacy, bool reportable)
101 | {
102 | _authenticationFlag = authentication;
103 | _privacyFlag = privacy;
104 | _reportableFlag = reportable;
105 | }
106 |
107 | ///
108 | /// Encode SNMP v3 message flag field
109 | ///
110 | /// Buffer to append encoded value to
111 | public override void encode(MutableByte buffer)
112 | {
113 | byte flag = 0x00;
114 | if (_authenticationFlag)
115 | flag |= FLAG_AUTH;
116 | if (_privacyFlag)
117 | flag |= FLAG_PRIV;
118 | if (_reportableFlag)
119 | flag |= FLAG_REPORTABLE;
120 | OctetString flagObject = new OctetString(flag);
121 | flagObject.encode(buffer);
122 | }
123 |
124 | ///
125 | /// Decode message flags from the BER encoded buffer starting at specified offset.
126 | ///
127 | /// BER encoded buffer
128 | /// Offset within the buffer to start decoding process
129 | /// Buffer position after the decoded value
130 | public override int decode(byte[] buffer, int offset)
131 | {
132 | // reset class values
133 | _authenticationFlag = false;
134 | _privacyFlag = false;
135 | _reportableFlag = false;
136 | OctetString flagObject = new OctetString();
137 | offset = flagObject.decode(buffer, offset);
138 | if (flagObject.Length > 0)
139 | {
140 | if ((flagObject[0] & FLAG_AUTH) != 0)
141 | _authenticationFlag = true;
142 | if ((flagObject[0] & FLAG_PRIV) != 0)
143 | _privacyFlag = true;
144 | if ((flagObject[0] & FLAG_REPORTABLE) != 0)
145 | _reportableFlag = true;
146 | }
147 | else
148 | {
149 | throw new SnmpDecodingException("Invalid SNMPv3 flag field.");
150 | }
151 | return offset;
152 | }
153 |
154 | ///
155 | /// Clone this class.
156 | ///
157 | /// Cloned class cast as Object
158 | public override object Clone()
159 | {
160 | return new MsgFlags(_authenticationFlag, _privacyFlag, _reportableFlag);
161 | }
162 |
163 | ///
164 | /// Return string representation of the object.
165 | ///
166 | /// String representation of the class values.
167 | public override string ToString()
168 | {
169 | return string.Format("Reportable {0} Authenticated {1} Privacy {2}", _reportableFlag.ToString(),
170 | _authenticationFlag.ToString(), _privacyFlag.ToString());
171 | }
172 | }
173 | }
174 |
--------------------------------------------------------------------------------
/security/PrivacyAES128.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// AES 128-bit key size privacy protocol implementation class.
21 | ///
22 | public class PrivacyAES128 : PrivacyAES
23 | {
24 | ///
25 | /// Standard constructor. Initializes the base class with key size 16 bytes (128-bit).
26 | ///
27 | public PrivacyAES128()
28 | : base(16)
29 | {
30 | }
31 |
32 | ///
33 | /// Returns privacy protocol name "AES128"
34 | ///
35 | public override string Name
36 | {
37 | get
38 | {
39 | return "AES128";
40 | }
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/security/PrivacyAES192.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Privacy class for AES 192-bit encryption. This is a helper class. Full functionality is implemented
21 | /// in parent class.
22 | ///
23 | public class PrivacyAES192 : PrivacyAES
24 | {
25 | ///
26 | /// Standard constructor initializes encryption key size in the parent class to 24 bytes (192 bit).
27 | ///
28 | public PrivacyAES192()
29 | : base(24)
30 | {
31 | }
32 |
33 | ///
34 | /// Returns privacy protocol name "AES192".
35 | ///
36 | public override string Name
37 | {
38 | get
39 | {
40 | return "AES192";
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/security/PrivacyAES256.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Privacy class for AES 256-bit encryption. This is a helper class. Full functionality is implemented
21 | /// in parent class.
22 | ///
23 | public class PrivacyAES256:PrivacyAES
24 | {
25 | ///
26 | /// Standard constructor initializes encryption key size in the parent class to 32 bytes (256 bit).
27 | ///
28 | public PrivacyAES256()
29 | : base(32)
30 | {
31 | }
32 |
33 | ///
34 | /// Returns privacy protocol name "AES256".
35 | ///
36 | public override string Name
37 | {
38 | get
39 | {
40 | return "AES256";
41 | }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/security/PrivacyProtocol.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | /// Privacy protocol helper class.
20 | ///
21 | /// This class is used to define privacy protocol encryption type in other
22 | /// classes using integer constants representing each protocol supported, and allows for easy instantiation
23 | /// of privacy protocol when used for encryption or decryption of data in a encryption method independent way.
24 | ///
25 | /// Example of how to use this class:
26 | ///
27 | /// int myPrivacyProtocol = PrivacyProtocol.AES128;
28 | ///
29 | /// IPrivacyProtocol privacyImplementation = PrivacyProtocol.GetInstance(myPrivacyProtocol);
30 | /// byte[] result = privacyImplementation.Encrypt(....);
31 | ///
32 | ///
33 | public sealed class PrivacyProtocol
34 | {
35 | ///
36 | /// Based on the supplied privacyProtocol, return instance of the privacy protocol implementation class.
37 | ///
38 | /// Privacy protocol code. Available protocols are ,
39 | /// , , and
40 | /// .
41 | /// Privacy protocol implementation class on success. If privacy protocol is
42 | /// then null is returned.
43 | public static IPrivacyProtocol GetInstance(PrivacyProtocols privProtocol)
44 | {
45 | if (privProtocol == PrivacyProtocols.None)
46 | return null;
47 | else if (privProtocol == PrivacyProtocols.DES)
48 | return new PrivacyDES();
49 | else if (privProtocol == PrivacyProtocols.AES128)
50 | return new PrivacyAES128();
51 | else if (privProtocol == PrivacyProtocols.AES192)
52 | return new PrivacyAES192();
53 | else if (privProtocol == PrivacyProtocols.AES256)
54 | return new PrivacyAES256();
55 | else if (privProtocol == PrivacyProtocols.TripleDES)
56 | return new Privacy3DES();
57 | return null;
58 | }
59 |
60 | ///
61 | /// Private constructor. This class cannot be instantiated.
62 | ///
63 | private PrivacyProtocol()
64 | {
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/security/PrivacyProtocols.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// Privacy protocol enumeration.
21 | ///
22 | public enum PrivacyProtocols
23 | {
24 | ///
25 | /// No privacy protocol. Data will not be encrypted
26 | ///
27 | None = 0,
28 | ///
29 | /// Privacy protocol is DES (56 bit encryption)
30 | ///
31 | DES,
32 | ///
33 | /// Privacy protocol is AES-128 (128 bit key). For implementation details, see and
34 | /// classes.
35 | ///
36 | AES128,
37 | ///
38 | /// Privacy protocol is AES-192 (128 bit key). For implementation details, see and
39 | /// classes.
40 | ///
41 | AES192,
42 | ///
43 | /// Privacy protocol is AES-156 (256 bit key). For implementation details, see and
44 | /// classes.
45 | ///
46 | AES256,
47 | ///
48 | /// Privacy protocol is Triple-DES. For implementation details see .
49 | ///
50 | TripleDES
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/security/SNMPV3ReportError.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 |
17 | namespace SnmpSharpNet
18 | {
19 | ///
20 | /// SNMP class translates SNMP version 3 report errors into error strings.
21 | ///
22 | public sealed class SNMPV3ReportError
23 | {
24 | private SNMPV3ReportError()
25 | {
26 | }
27 |
28 | ///
29 | /// Search variable bindings list in the passed packet for usm error OIDs and return
30 | /// error string value.
31 | ///
32 | /// Packet to search for error OIDs
33 | /// Error string if found in the packet, otherwise an empty string.
34 | public static string TranslateError(SnmpV3Packet packet)
35 | {
36 | foreach (Vb v in packet.Pdu.VbList)
37 | {
38 | if (v.Oid.Compare(SnmpConstants.usmStatsUnsupportedSecLevels) == 0)
39 | {
40 | return string.Format("usmStatsUnsupportedSecLevels: {0}", v.Value.ToString());
41 | }
42 | else if (v.Oid.Compare(SnmpConstants.usmStatsNotInTimeWindows) == 0)
43 | {
44 | return string.Format("usmStatsNotInTimeWindows: {0}", v.Value.ToString());
45 | }
46 | else if (v.Oid.Compare(SnmpConstants.usmStatsUnknownSecurityNames) == 0)
47 | {
48 | return string.Format("usmStatsUnknownSecurityNames: {0}", v.Value.ToString());
49 | }
50 | else if (v.Oid.Compare(SnmpConstants.usmStatsUnknownEngineIDs) == 0)
51 | {
52 | return string.Format("usmStatsUnknownEngineIDs: {0}", v.Value.ToString());
53 | }
54 | else if (v.Oid.Compare(SnmpConstants.usmStatsWrongDigests) == 0)
55 | {
56 | return string.Format("usmStatsWrongDigests: {0}", v.Value.ToString());
57 | }
58 | else if (v.Oid.Compare(SnmpConstants.usmStatsDecryptionErrors) == 0)
59 | {
60 | return string.Format("usmStatsDecryptionErrors: {0}", v.Value.ToString());
61 | }
62 | else if (v.Oid.Compare(SnmpConstants.snmpUnknownSecurityModels) == 0)
63 | {
64 | return string.Format("snmpUnknownSecurityModels: {0}", v.Value.ToString());
65 | }
66 | else if (v.Oid.Compare(SnmpConstants.snmpInvalidMsgs) == 0)
67 | {
68 | return string.Format("snmpInvalidMsgs: {0}", v.Value.ToString());
69 | }
70 | else if (v.Oid.Compare(SnmpConstants.snmpUnknownPDUHandlers) == 0)
71 | {
72 | return string.Format("snmpUnknownPDUHandlers: {0}", v.Value.ToString());
73 | }
74 | }
75 | return "";
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/security/ScopedPdu.cs:
--------------------------------------------------------------------------------
1 | // This file is part of SNMP#NET.
2 | //
3 | // SNMP#NET is free software: you can redistribute it and/or modify
4 | // it under the terms of the GNU Lesser Public License as published by
5 | // the Free Software Foundation, either version 3 of the License, or
6 | // (at your option) any later version.
7 | //
8 | // SNMP#NET is distributed in the hope that it will be useful,
9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | // GNU General Public License for more details.
12 | //
13 | // You should have received a copy of the GNU General Public License
14 | // along with SNMP#NET. If not, see .
15 | //
16 | using System;
17 | namespace SnmpSharpNet
18 | {
19 | /// SNMP Version 3 Scoped Protocol Data Unit.
20 | ///
21 | /// ScopedPdu extends the class by adding SNMP version 3 specific Context Engine Id and Context Name
22 | /// variables to the beginning of the packet.
23 | ///
24 | /// Context engine id is retrieved from the agent using the SNMP version 3 standard defined discovery process. Context
25 | /// name is used to define which subsection of the agents MIB user is allowed (or wants) to access.
26 | ///
27 | /// When creating a new ScopedPdu, for a valid request, ContextEngineId value has to be set for a valid reply to be
28 | /// received. Context value is implementation specific (depends on the configuration of the agent) and might not be
29 | /// required for a successful request.
30 | ///
31 | public class ScopedPdu: Pdu
32 | {
33 | #region Private variables
34 |
35 | ///
36 | /// Context Engine Id variable.
37 | ///
38 | protected OctetString _contextEngineId;
39 | ///
40 | /// Context name variable
41 | ///
42 | protected OctetString _contextName;
43 |
44 | #endregion
45 |
46 | #region Properties
47 | ///
48 | /// Get/Set context engine id value.
49 | ///
50 | public OctetString ContextEngineId
51 | {
52 | get { return _contextEngineId; }
53 | }
54 |
55 | ///
56 | /// Get/Set context name value
57 | ///
58 | public OctetString ContextName
59 | {
60 | get { return _contextName; }
61 | }
62 |
63 | #endregion
64 |
65 | #region Constructor(s)
66 |
67 | ///
68 | /// Standard constructor.
69 | ///
70 | ///
71 | /// Intializes the ScopedPdu type to SNMP-GET. For details see base
72 | /// class standard constructor definition.
73 | ///
74 | /// Context engine id and name variables are initialized to 0 length values.
75 | ///
76 | public ScopedPdu()
77 | : base()
78 | {
79 | _contextEngineId = new OctetString();
80 | _contextName = new OctetString();
81 | }
82 |
83 | ///
84 | /// Constructor.
85 | ///
86 | /// Pdu type value. For available types see .
87 | public ScopedPdu(PduType pduType)
88 | : base(pduType)
89 | {
90 | _contextEngineId = new OctetString();
91 | _contextName = new OctetString();
92 | }
93 |
94 | /// Constructor.
95 | ///
96 | /// Standard constructor that sets ScopedPdu request type and request id. For valid types see .
97 | ///
98 | /// By default, requestId value is set to a random value. Second argument allows caller to specify request
99 | /// id for this packet
100 | ///
101 | /// Pdu type value.
102 | /// Request id for the ScopedPdu instance.
103 | public ScopedPdu(PduType pduType, int requestId)
104 | : base(pduType)
105 | {
106 | _requestId.Value = requestId;
107 | _contextEngineId = new OctetString();
108 | _contextName = new OctetString();
109 | }
110 |
111 | ///
112 | /// Constructor.
113 | ///
114 | /// Initialize class from this class
115 | public ScopedPdu(Pdu pdu)
116 | : base(pdu)
117 | {
118 | _contextEngineId = new OctetString();
119 | _contextName = new OctetString();
120 | }
121 |
122 | #endregion
123 |
124 | #region Encode and decode
125 |
126 | ///
127 | /// Convert into a BER encoded byte array. Resulting byte array is appended
128 | /// to the argument specified class.
129 | ///
130 | /// Privacy operations are not performed by this method. Value encoded and returned by this method is
131 | /// suitable for sending in NoAuthNoPriv or AuthNoPriv security configurations. If privacy is required,
132 | /// caller will have to perform encryption and decryption operations after BER encoding is performed.
133 | ///
134 | /// In privacy protected SNMP version 3 packets, ScopedPdu is 1) encrypted using configured encryption
135 | /// method, 2) added to a field, and 3) appended to the data buffer.
136 | ///
137 | /// Because privacy operation is intrusive, it is recommended that BER encoding of the ScopedPdu packet
138 | /// is stored in a temporary class, where it can be privacy protected and
139 | /// added to the class for final encoding into the target SNMP v3 packet.
140 | ///
141 | /// class passed by reference that encoded ScopedPdu
142 | /// value is appended to.
143 | public override void encode(MutableByte buffer)
144 | {
145 | MutableByte tmp = new MutableByte();
146 | _contextEngineId.encode(tmp);
147 | _contextName.encode(tmp);
148 | // Encode base
149 | base.encode(tmp);
150 | BuildHeader(buffer, SnmpConstants.SMI_SEQUENCE, tmp.Length);
151 | buffer.Append(tmp);
152 | }
153 |
154 | ///
155 | /// Decode BER encoded values. This method does not perform SNMP v3 privacy operations
156 | /// and is not aware of privacy requirements.
157 | ///
158 | /// To decode a privacy protected SNMP v3 packet, you will need to a) extract value
159 | /// holding encrypted data, b) decrypt the encrypted ScopedPdu data into an unecrypted
160 | /// byte array, c) pass unencrypted and BER encoded byte array to this method for
161 | /// final data conversion from BER into individual sequences and variables.
162 | ///
163 | /// Buffer holding BER encoded data
164 | /// Offset within the buffer BER encoded data begins.
165 | /// Offset position after parsed ScopedPdu
166 | /// Error was encountered when decoding the PDU
167 | /// Thrown when buffer is too short to contain the PDU
168 | public override int decode(byte[] buffer, int offset)
169 | {
170 | int length;
171 | byte sequenceType = ParseHeader(buffer, ref offset, out length);
172 | if (sequenceType != SnmpConstants.SMI_SEQUENCE)
173 | throw new SnmpDecodingException("Invalid ScopedPdu sequence detected. Invalid ScopedPdu encoding.");
174 | // verify packet can match parsed length
175 | if (length > (buffer.Length - offset))
176 | throw new OverflowException("SNMP packet too short.");
177 |
178 | // Reset scoped pdu specific variables
179 | _contextEngineId.Reset();
180 | _contextName.Reset();
181 | // parse scoped pdu specific variables
182 | offset = _contextEngineId.decode(buffer, offset);
183 | offset = _contextName.decode(buffer, offset);
184 | // decode base pdu
185 | offset = base.decode(buffer, offset);
186 |
187 | return offset;
188 | }
189 |
190 | #endregion Encode and decode
191 |
192 | }
193 | }
194 |
--------------------------------------------------------------------------------