⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 usmmib.java

📁 你个snmp的源码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*_############################################################################
  _##
  _##  SNMP4J-Agent - UsmMIB.java
  _##
  _##  Copyright 2005-2006  Frank Fock (SNMP4J.org)
  _##
  _##  Licensed under the Apache License, Version 2.0 (the "License");
  _##  you may not use this file except in compliance with the License.
  _##  You may obtain a copy of the License at
  _##
  _##      http://www.apache.org/licenses/LICENSE-2.0
  _##
  _##  Unless required by applicable law or agreed to in writing, software
  _##  distributed under the License is distributed on an "AS IS" BASIS,
  _##  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  _##  See the License for the specific language governing permissions and
  _##  limitations under the License.
  _##
  _##########################################################################*/


package org.snmp4j.agent.mo.snmp;

import org.snmp4j.agent.*;
import org.snmp4j.agent.mo.*;
import org.snmp4j.agent.request.*;
import org.snmp4j.event.*;
import org.snmp4j.mp.*;
import org.snmp4j.security.*;
import org.snmp4j.smi.*;
import org.snmp4j.PDU;
import org.snmp4j.agent.mo.DefaultMOTable.ChangeSet;

/**
 * The <code>UsmMIB</code> implements the SNMP-USER-BASED-SM-MIB defined in
 * RFC 3414. The MIB implementation is backed by a {@link USM} instance.
 * The configuration of the user based security model can be changed
 * programatically by changing the underlying {@link USM} or via SNMP but at
 * least one user must be created programatically in order to allow any access
 * to the agent via SNMP.
 * <p>
 * When modifying the USM after having created this MIB, you will have to
 * register this object as {@link UsmUserListener} to the USM.
 * <p>
 * By using SNMP, a new users can only be created by cloning it from an existing
 * user with the same or higher security level.
 *
 * @author Frank Fock
 * @version 1.0
 */
public class UsmMIB
    implements
    MOGroup,
    CounterListener,
    MOValueValidationListener,
    UsmUserListener, RowStatusListener {

  private static final OID noAuthProtocol =
      new OID(new int[] {1,3,6,1,6,3,10,1,1,1});
  private static final OID noPrivProtocol =
      new OID(new int[] {1,3,6,1,6,3,10,1,2,1});

  private static final OID usmUserSpinLockOID =
      new OID(new int[] { 1,3,6,1,6,3,15,1,2,1,0 });
  private static final OID usmUserEntryOID =
      new OID(new int[] { 1,3,6,1,6,3,15,1,2,2,1 });


  static final int colUsmUserSecurityName = 0;
  static final int colUsmUserCloneFrom = 1;
  static final int colUsmUserAuthProtocol = 2;
  static final int colUsmUserAuthKeyChange = 3;
  static final int colUsmUserOwnAuthKeyChange = 4;
  static final int colUsmUserPrivProtocol = 5;
  static final int colUsmUserPrivKeyChange = 6;
  static final int colUsmUserOwnPrivKeyChange = 7;
  static final int colUsmUserPublic = 8;
  static final int colUsmUserStorageType = 9;
  static final int colUsmUserStatus = 10;

  private static final int[][] keyChangeColumns =
      { {colUsmUserAuthKeyChange, colUsmUserOwnAuthKeyChange},
        {colUsmUserPrivKeyChange, colUsmUserOwnPrivKeyChange}
  };
  private USM usm;
  private SecurityProtocols securityProtocols;

  private static final OID usmStatsPrefix =
      new OID(SnmpConstants.usmStatsUnsupportedSecLevels.getValue(), 0,
              SnmpConstants.usmStatsUnsupportedSecLevels.size()-2);

  private static final OID[] usmStatOIDs = new OID[] {
      SnmpConstants.usmStatsUnsupportedSecLevels,
      SnmpConstants.usmStatsNotInTimeWindows,
      SnmpConstants.usmStatsUnknownUserNames,
      SnmpConstants.usmStatsUnknownEngineIDs,
      SnmpConstants.usmStatsWrongDigests,
      SnmpConstants.usmStatsDecryptionErrors
  };

  private MOScalar[] usmStats;
  private TestAndIncr usmUserSpinLock;
  private DefaultMOTable usmUserEntry;
  private UsmTableModel usmUserTableModel;

  /**
   * Creates a USM MIB implementation connected to the supplied USM. The MIB
   * contents will reflect any changes to the USM after completion of this
   * constructor if you register this object as {@link UsmUserListener} to the
   * USM!
   * @param usm
   *   a User-based Security Model.
   * @param securityProtocols
   *   the supported <code>SecurityProtocols</code>.
   */
  public UsmMIB(USM usm, SecurityProtocols securityProtocols) {
    this.usm = usm;
    this.securityProtocols = securityProtocols;
    usm.getCounterSupport().addCounterListener(this);
    createUsmStats();
    createUsmUser();
  }

  private void createUsmUser() {
    usmUserSpinLock = new TestAndIncr(usmUserSpinLockOID);
    MOTableSubIndex[] usmUserSubIndexes = new MOTableSubIndex[] {
        new MOTableSubIndex(SMIConstants.SYNTAX_OCTET_STRING, 5, 32),
        new MOTableSubIndex(SMIConstants.SYNTAX_OCTET_STRING, 1, 32)
    };
    MOColumn[] usmUserColumns = new MOColumn[] {
        new SnmpAdminString(colUsmUserSecurityName + 3,
                            MOAccessImpl.ACCESS_READ_ONLY,
                            null, false),
        new UsmRowPointer(colUsmUserCloneFrom + 3,
                          MOAccessImpl.ACCESS_READ_CREATE,
                          null, true),
        new AutonomousType(colUsmUserAuthProtocol + 3,
                           MOAccessImpl.ACCESS_READ_CREATE,
                           noAuthProtocol, true),
        new UsmKeyChange(colUsmUserAuthKeyChange + 3,
                         MOAccessImpl.ACCESS_READ_CREATE,
                         UsmKeyChange.AUTH_KEY_CHANGE),
        new UsmOwnKeyChange(colUsmUserOwnAuthKeyChange + 3,
                            MOAccessImpl.ACCESS_READ_CREATE,
                            UsmKeyChange.AUTH_KEY_CHANGE),
        new AutonomousType(colUsmUserPrivProtocol + 3,
                           MOAccessImpl.ACCESS_READ_CREATE,
                           noPrivProtocol, true),
        new UsmKeyChange(colUsmUserPrivKeyChange + 3,
                         MOAccessImpl.ACCESS_READ_CREATE,
                         UsmKeyChange.PRIV_KEY_CHANGE),
        new UsmOwnKeyChange(colUsmUserOwnPrivKeyChange + 3,
                            MOAccessImpl.ACCESS_READ_CREATE,
                            UsmKeyChange.PRIV_KEY_CHANGE),
        new SnmpAdminString(colUsmUserPublic + 3,
                            MOAccessImpl.ACCESS_READ_CREATE,
                            new OctetString(), true, 0, 32),
        new StorageType(colUsmUserStorageType + 3,
                        MOAccessImpl.ACCESS_READ_CREATE,
                        new Integer32(StorageType.nonVolatile), true),
        new RowStatus(colUsmUserStatus + 3, MOAccessImpl.ACCESS_READ_CREATE)
    };
    MOTableIndex usmUserIndex = new MOTableIndex(usmUserSubIndexes, false);
    usmUserTableModel = new UsmTableModel(usmUserIndex);
    usmUserEntry = new DefaultMOTable(usmUserEntryOID, usmUserIndex,
                                      usmUserColumns, usmUserTableModel);
    ((AutonomousType)
     usmUserColumns[colUsmUserAuthProtocol]).addMOValueValidationListener(this);
    ((AutonomousType)
     usmUserColumns[colUsmUserPrivProtocol]).addMOValueValidationListener(this);
    ((RowStatus)usmUserColumns[colUsmUserStatus]).addRowStatusListener(this);
    ((UsmRowPointer)
     usmUserColumns[colUsmUserCloneFrom]).setTargetTable(usmUserEntry);
  }

  private void createUsmStats() {
    usmStats = new MOScalar[usmStatOIDs.length];
    for (int i=0; i<usmStats.length; i++) {
      usmStats[i] = new MOScalar(usmStatOIDs[i], MOAccessImpl.ACCESS_READ_ONLY,
                                 new Counter32(0));
    }
  }

  public void registerMOs(MOServer server, OctetString context) throws
      DuplicateRegistrationException {
    for (int i=0; i < usmStats.length; i++) {
      server.register(usmStats[i], context);
    }
    server.register(usmUserSpinLock, context);
    server.register(usmUserEntry, context);
  }

  public void unregisterMOs(MOServer server, OctetString context) {
    for (int i=0; i < usmStats.length; i++) {
      server.unregister(usmStats[i], context);
    }
    server.unregister(usmUserSpinLock, context);
    server.unregister(usmUserEntry, context);
  }

  public void incrementCounter(CounterEvent event) {
    if ((event.getOid().startsWith(usmStatsPrefix)) &&
        (event.getOid().size() > usmStatsPrefix.size())) {
      Counter32 current = (Counter32)
           usmStats[event.getOid().get(usmStatsPrefix.size())-1].getValue();
      current.increment();
      event.setCurrentValue((Counter32)current.clone());
    }
  }


  public void validate(MOValueValidationEvent validationEvent) {
    if (validationEvent.getSource() instanceof MOColumn) {
      MOColumn col = (MOColumn) validationEvent.getSource();
      switch (col.getColumnID()-4) {
        case colUsmUserAuthProtocol: {
          OID value = (OID)validationEvent.getNewValue();
          if (!noAuthProtocol.equals(value)) {
            AuthenticationProtocol authProtocol =
                SecurityProtocols.getInstance().
                getAuthenticationProtocol((OID) validationEvent.getNewValue());
            if (authProtocol == null) {
              validationEvent.setValidationStatus(SnmpConstants.
                                                  SNMP_ERROR_WRONG_VALUE);
            }
          }
          break;
        }
        case colUsmUserPrivProtocol: {
          OID value = (OID)validationEvent.getNewValue();
          if (!noPrivProtocol.equals(value)) {
            PrivacyProtocol privProtocol =
                SecurityProtocols.getInstance().getPrivacyProtocol(value);
            if (privProtocol == null) {
              validationEvent.setValidationStatus(SnmpConstants.
                                                  SNMP_ERROR_WRONG_VALUE);
            }
          }
          break;
        }
      }
    }
  }

  private Variable[] getValuesFromUsmUser(UsmUserEntry user) {
    Variable[] row = new Variable[usmUserEntry.getColumnCount()];
    int n = 0;
    row[n++] = user.getUsmUser().getSecurityName();
    row[n++] = null;
    row[n++] = user.getUsmUser().getAuthenticationProtocol();
    row[n++] = null;
    row[n++] = null;
    row[n++] = user.getUsmUser().getPrivacyProtocol();
    row[n++] = null;
    row[n++] = null;
    row[n++] = new OctetString();
    row[n++] = new Integer32(StorageType.nonVolatile);
    row[n++] = new Integer32(RowStatus.active);
    return row;
  }

  private OID createIndex(OctetString engineID, OctetString userName) {
    if (engineID.length() == 0) {
      engineID = usm.getLocalEngineID();
    }
    OID index = engineID.toSubIndex(false);
    index.append(userName.toSubIndex(false));
    return index;
  }

  public void usmUserChange(UsmUserEvent event) {
    switch (event.getType()) {
      case UsmUserEvent.USER_ADDED: {
        Variable[] values = getValuesFromUsmUser(event.getUser());
        OID index = createIndex(event.getUser().getEngineID(),
                                event.getUser().getUserName());
        MOMutableRow2PC row = (MOMutableRow2PC)
            usmUserTableModel.createRow(index, values);
        usmUserTableModel.addRow(row);
        break;
      }
      case UsmUserEvent.USER_REMOVED: {
        OID index = createIndex(event.getUser().getEngineID(),
                                event.getUser().getUserName());
        usmUserTableModel.removeRow(index);
      }
    }
  }

  private static byte[] getKey(UsmUserEntry entry, int authVsPriv) {
    return (authVsPriv == 0) ?

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -