markabrahams / node-net-snmp

JavaScript implementation of the Simple Network Management Protocol (SNMP)
207 stars 97 forks source link

SNMP v3 with context - only first (discovery) packet works #198

Closed gavinaiken closed 2 years ago

gavinaiken commented 2 years ago

I'm having trouble where I create an SNMP v3 session with a context, and only the first packet gets a good response - any subsequent packets give me an AuthorizationError. Here's a very simple bit of code to illustrate the problem - the first get works and the second one fails.

import snmp from 'net-snmp';

const options = {
    context: 'CONTEXTA',
    port: 161,
    retries: 0,
    transport: 'udp4',
    trapPort: 162,
    timeout: 5000,
    version: snmp.Version3,
};

const host = '127.0.0.1';

const user = {
    name: 'v3user2',
    level: snmp.SecurityLevel.authPriv,
    authProtocol: snmp.AuthProtocols.sha,
    authKey: 'XXX',
    privProtocol: snmp.PrivProtocols.aes,
    privKey: 'XXX',
};

const oids = [
    '1.3.6.1.2.1.1.2.0',
    '1.3.6.1.2.1.1.3.0',
    '1.3.6.1.2.1.1.4.0',
    '1.3.6.1.2.1.1.5.0',
    '1.3.6.1.2.1.1.6.0',
    '1.3.6.1.2.1.1.1.0',
];

let session = snmp.createV3Session(host, user, options);

// handle errors emitted by the session
session.on('error', function (error) {
    console.error(`SNMP session on host ${host} emitted an error:`, error);
    session.close();
});

function printVarbinds(varbinds) {
    if (!Array.isArray(varbinds)) {
        console.log('varbinds', varbinds);
        return;
    }
    varbinds.forEach(v => {
        console.log(v.oid, ' : ', v.value.toString());
    });
}

session.get(oids, function (error, varbinds) {
    console.log('error', error);
    printVarbinds(varbinds);

    console.log('-----\n\n\n');

    session.get(oids, function (error, varbinds) {
        console.log('error', error);
        printVarbinds(varbinds);
    });
});
markabrahams commented 2 years ago

Great - thanks for logging this @gavinaiken, and for the PR to fix. I've merged this now and published in version 3.6.1 of the npm.