Showing posts with label SNMP4J. Show all posts
Showing posts with label SNMP4J. Show all posts

3.11.10

Trap in SNMP4j-Agent

SNMP Trap is something very interesting. The Agent is responsible for sending trap/notification, while the client works in the daemon mode to receive trap messages.

Who is the server? Well, server is not a concept in SNMP v1 and v2. People call them agents.

How Trap is Implemented in SNMP4J Agent?

That is a good question. Just take a look at BaseAgent. Here is some excerpt from SNMP4J Agent 1.4.1.

134   /**
135 * Initialize transport mappings, message dispatcher, basic MIB modules,
136 * proxy forwarder, VACM and USM security, and custom MIB modules and objects
137 * provided by sub-classes.
138 *
139 * @throws IOException
140 * if initialization fails because transport initialization fails.
141 */
142 public void init() throws IOException {
143 agentState = STATE_INIT_STARTED;
144 initTransportMappings();
145 initMessageDispatcher();
146 server.addContext(new OctetString());
147 snmpv2MIB = new SNMPv2MIB(sysDescr, sysOID, sysServices);
148
149 // register Snmp counters for updates
150 dispatcher.addCounterListener(snmpv2MIB);
151 agent.addCounterListener(snmpv2MIB);
152 snmpFrameworkMIB =
153 new SnmpFrameworkMIB((USM)
154 mpv3.getSecurityModel(SecurityModel.SECURITY_MODEL_USM),
155 dispatcher.getTransportMappings());
156 usmMIB = new UsmMIB(usm, SecurityProtocols.getInstance());
157 usm.addUsmUserListener(usmMIB);
158
159 vacmMIB = new VacmMIB(new MOServer[] { server });
160 snmpTargetMIB = new SnmpTargetMIB(dispatcher);
161 snmpNotificationMIB = new SnmpNotificationMIB();
162 snmpCommunityMIB = new SnmpCommunityMIB(snmpTargetMIB);
163 initConfigMIB();
164 snmpProxyMIB = new SnmpProxyMIB();
165 notificationOriginator =
166 new NotificationOriginatorImpl(session, vacmMIB,
167 snmpv2MIB.getSysUpTime(),
168 snmpTargetMIB, snmpNotificationMIB);

169 snmpv2MIB.setNotificationOriginator(agent);
170
171 setupDefaultProxyForwarder();
172 // add USM users
173 addUsmUser(usm);
174 // add SNMPv1/v2c community to SNMPv3 security name mappings
175 addCommunities(snmpCommunityMIB);
176 addViews(vacmMIB);
177 addNotificationTargets(snmpTargetMIB, snmpNotificationMIB);
178
179 registerSnmpMIBs();
180 }


At line 161, an SnmpNotificationMIB instance is created. From line 165 to 168, a NotificationOriginator is created by using NotificationOriginatorImpl. Line 169 sets up the notification originator for SNMPv2 MIB object, while line 177 calls the abstract method, addNotificationTargets() to add more things into the target MIB and notification MIB.


addNotificationTargets()?


If you are using BaseAgent just like I do now, overriding addNotificationTargets() method could be a very good access point for your trap targets.This method is abstract in BaseAgent, and you must override them, although you can just put it as empty in your derived class.


Target MIB?


The method addNotificationTargets() uses two parameters: Target MIB and Notification MIB.


Target MIB is an instance of SnmpTargetMIB class. It is initialized at line 160 above with a dispatcher, which is an instance of MessageDispatcherImpl, initialized by initMessageDispatcher().


From the SNMP protocol’s point of view, SnmpTargetMIB takes care of SNMP Target Objects in SNMP-TARGET-MIB, which is a version 2 MIB.


OID Base









snmpTargetObjects
1.3.6.1.6.3.12.1

iso(1). org(3). dod(6). internet(1). snmpV2(6). snmpModules(3). snmpTargetMIB(12). snmpTargetObjects(1)


Details










































































































































































































snmpTargetObjectsGROUP1.3.6.1.6.3.12.1
iso(1). org(3). dod(6). internet(1). snmpV2(6). snmpModules(3). snmpTargetMIB(12). snmpTargetObjects(1)
  snmpTargetSpinLockSCALARread-writeTestAndIncr1.3.6.1.6.3.12.1.1.0
  snmpTargetAddrTableTABLEnot-accessibleSEQUENCE OF1.3.6.1.6.3.12.1.2
    snmpTargetAddrEntryENTRYnot-accessibleSnmpTargetAddrEntry1.3.6.1.6.3.12.1.2.1
      snmpTargetAddrNameTABULARnot-accessibleSnmpAdminString ( 1..32 )1.3.6.1.6.3.12.1.2.1.1
      snmpTargetAddrTDomainTABULARread-createTDomain1.3.6.1.6.3.12.1.2.1.2
      snmpTargetAddrTAddressTABULARread-createTAddress1.3.6.1.6.3.12.1.2.1.3
      snmpTargetAddrTimeoutTABULARread-createTimeInterval1.3.6.1.6.3.12.1.2.1.4
      snmpTargetAddrRetryCountTABULARread-createInteger32 ( 0..255 )1.3.6.1.6.3.12.1.2.1.5
      snmpTargetAddrTagListTABULARread-createSnmpTagList1.3.6.1.6.3.12.1.2.1.6
      snmpTargetAddrParamsTABULARread-createSnmpAdminString ( 1..32 )1.3.6.1.6.3.12.1.2.1.7
      snmpTargetAddrStorageTypeTABULARread-createStorageType1.3.6.1.6.3.12.1.2.1.8
      snmpTargetAddrRowStatusTABULARread-createRowStatus1.3.6.1.6.3.12.1.2.1.9
  snmpTargetParamsTableTABLEnot-accessibleSEQUENCE OF1.3.6.1.6.3.12.1.3
    snmpTargetParamsEntryENTRYnot-accessibleSnmpTargetParamsEntry1.3.6.1.6.3.12.1.3.1
      snmpTargetParamsNameTABULARnot-accessibleSnmpAdminString ( 1..32 )1.3.6.1.6.3.12.1.3.1.1
      snmpTargetParamsMPModelTABULARread-createSnmpMessageProcessingModel1.3.6.1.6.3.12.1.3.1.2
      snmpTargetParamsSecurityModelTABULARread-createSnmpSecurityModel ( 1..2147483647 )1.3.6.1.6.3.12.1.3.1.3
      snmpTargetParamsSecurityNameTABULARread-createSnmpAdminString1.3.6.1.6.3.12.1.3.1.4
      snmpTargetParamsSecurityLevelTABULARread-createSnmpSecurityLevel1.3.6.1.6.3.12.1.3.1.5
      snmpTargetParamsStorageTypeTABULARread-createStorageType1.3.6.1.6.3.12.1.3.1.6
      snmpTargetParamsRowStatusTABULARread-createRowStatus1.3.6.1.6.3.12.1.3.1.7
  snmpUnavailableContextsSCALARread-onlyCounter321.3.6.1.6.3.12.1.4.0
  snmpUnknownContextsSCALARread-onlyCounter321.3.6.1.6.3.12.1.5.0

What can I do with SNMP4J Agent?


You might probably don’t care about SNMP Target MIB. All you need could only by how to use SNMP4J Agent. Good.


Although the Java API documentation for SNMP4J Agent is very useless, they provided meaningful naming, as well as, and more importantly, source code. That is way we like open-source, right?


 


Notification MIB?

11.10.10

SNMP Trap Example Shipped with SNMP4J

http://www.snmp4j.org/doc/org/snmp4j/package-summary.html

SNMPv1 TRAP PDU

import org.snmp4j.PDUv1;
...
PDUv1 pdu = new PDUv1();
pdu.setType(PDU.V1TRAP);
pdu.setGenericTrap(PDUv1.COLDSTART);
...

SNMPv2c/SNMPv3 INFORM PDU

import org.snmp4j.ScopedPDU;
...
ScopedPDU pdu = new ScopedPDU();
pdu.setType(PDU.INFORM);
// sysUpTime
long sysUpTime = (System.currentTimeMillis() - startTime) / 10;
pdu.add(new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(sysUpTime)));
pdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, SnmpConstants.linkDown));
// payload
pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.1"+downIndex),
new Integer32(downIndex)));
...

Multi Threaded Trap Receiver using SNMP4J

Just a bookmark here. Please refer to the original blog for it.

http://www.ashishpaliwal.com/blog/2008/12/multi-threaded-trap-receiver-using-snmp4j/

Implementing Trap Sender using SNMP4J

In this post, we shall implement a Trap Sender using SNMP4J. We may choose to use Apache MINA for sending Traps or can resort to using DatagramSocket class directly.

This shall be the logical flow of the implementation

  • Get the encoded Trap Data
  • Send the Trap

Lets look at the first component, on getting the encoded Trap data

The code snippet above shows a simple way of creating and encoding a Trap PDU. Essentially, we create an instance of PDU class and sets the type as Trap. This is important, else SNMP4J shall throw an exception. Thereafter, we can set the trap parameters. Here, we have hardcoded the parameters, there can be custom implementations that can take these from config files or from UI. After setting the parameters, we just call the encode function passing the Output stream and collect the byte array to be sent.

Sending part is even simpler     

 

http://www.ashishpaliwal.com/blog/2008/10/implementing-trap-sender-using-snmp4j/

30.9.10

The Simplest SNMP Agent Implementation Using SNMP4J Agent

If you are looking for a very simple SNMP Agent implementation using SNMP4J Agent library, here it .

http://code.google.com/p/springside-sub/source/browse/#svn/trunk/tiny-examples/simple-snmp-agent

Essential Elements

To start an SNMP Agent, I need the following essential elements:

  • Daemon information and daemon
  • Authentication

With SNMP4J, you can find the following terminologies / mappings:

Authentication Community
Network Daemon Transport

BaseAgent

SNMP4JAgentAPI-ClassOverview_1_0-BaseAgent

BaseAgent is usually the start point for programming an SNMP4J Agent. And it is a good idea to understand all properties of this class. Interestingly,

  • MIBs
  • Maanageable Object Server
  • Proxy Forwarder

MIBs

  protected SNMPv2MIB snmpv2MIB;
protected SnmpFrameworkMIB snmpFrameworkMIB;
protected SnmpTargetMIB snmpTargetMIB;
protected SnmpNotificationMIB snmpNotificationMIB;
protected SnmpProxyMIB snmpProxyMIB;
protected SnmpCommunityMIB snmpCommunityMIB;
protected Snmp4jLogMib snmp4jLogMIB;
protected Snmp4jConfigMib snmp4jConfigMIB;
protected UsmMIB usmMIB;
protected VacmMIB vacmMIB;

29.9.10

Starts the Test Agent of SNMP4J-Agent Project

If you want to start the test agent of SNMP4J-Agent simply by entering the following command:

$mvn exec:java –Dexec.mainClass=org.snmp4j.agent.test.TestAgent

You will get the following Error:

java.lang.NoClassDefFoundError: org/snmp4j/event/CounterListener
Caused by: java.lang.ClassNotFoundException: org.snmp4j.event.CounterListener
        at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
Could not find the main class: org.snmp4j.agent.test.TestAgent.  Program will exit.
Exception in thread "main"

 

To solve the problem, please modify the pom.xml file and remove the scope of two dependencies:

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
                        <!--
            <scope>provided</scope>
                        -->
        </dependency>
        <dependency>
            <groupId>org.snmp4j</groupId>
            <artifactId>snmp4j</artifactId>
            <version>1.11.1</version>
                        <!--
            <scope>provided</scope>
                        -->
        </dependency>

The Batch Command to Execute SNM4J

@echo off

set CMD_LINE_ARGS=
:setArgs
if ""%1""=="""" goto doneSetArgs
set CMD_LINE_ARGS=%CMD_LINE_ARGS% %1
shift
goto setArgs
:doneSetArgs
rem %CMD_LINE_ARGS%
java -cp lib\log4j-1.2.14.jar;dist\snmp4j-1.11.1.jar org.snmp4j.tools.console.SnmpRequest %CMD_LINE_ARGS%

Basic Encoding Rule (BER)

http://en.wikipedia.org/wiki/Basic_Encoding_Rules

 

The Basic Encoding Rules (BER) is one of the encoding formats defined as part of the ASN.1 standard specified by the IT in X.690.

TLV encoding

TLV: Type + Length + Value

I developed many protocols using TLV encoding in my previous jobs. It’s very flexible and efficient.

However, in my designs, the structures are flat. The encoding of a PDU consists of cascaded TLV encodings, encapsulating types are SEQUENCE, SET and CHOICE.

More over, in my designs, types are 32 bits integers, while other people develop the type as an octet specifying the characteristics of the value field. The reason is very simple: I usually don’t care too much about the network efficiency, while the public protocol designer must take good care about it.

Class bits

00 – Universal

The value is of a type native to ASN.1.

01 – Application

The Application class is only valid for one specific application.

10 – Context specific

Context-specific depends on the context (such as within sequence, set of choice)

11 – Private

Private can be defined in private specifications.

Universal Class Tags

http://luca.ntop.org/Teaching/Appunti/asn1.html

Name P/C Number (decimal) Number (hexadecimal)
EOC (End-of-Content) P 0 0
BOOLEAN P 1 1
INTEGER P 2 2
BIT STRING P/C 3 3
OCTET STRING P/C 4 4
NULL P 5 5
OBJECT IDENTIFIER P 6 6
Object Descriptor P 7 7
EXTERNAL C 8 8
REAL (float) P 9 9
ENUMERATED P 10 A
EMBEDDED PDV C 11 B
UTF8String P/C 12 C
RELATIVE-OID P 13 D
SEQUENCE and SEQUENCE OF C 16 10
SET and SET OF C 17 11
NumericString P/C 18 12
PrintableString P/C 19 13
T61String P/C 20 14
VideotexString P/C 21 15
IA5String P/C 22 16
UTCTime P/C 23 17
GeneralizedTime P/C 24 18
GraphicString P/C 25 19
VisibleString P/C 26 1A
GeneralString P/C 27 1B
UniversalString P/C 28 1C
CHARACTER STRING P/C 29 1D
BMPString P/C 30 1E

Usage

Despite its perceived problems, BER is a popular format for transmitting data, particularly in systems with different native data encodings.

  • The SNMP protocol specifies ASN.1 with BER as its required encoding scheme.