Esempio n. 1
0
 /** For SNMP Runtime private use only. */
 public void encodeVarBindList(BerEncoder benc, SnmpVarBind[] varBindList)
     throws SnmpStatusException, SnmpTooBigException {
   //
   // Remember: the encoder does backward encoding
   //
   int encodedVarBindCount = 0;
   try {
     benc.openSequence();
     if (varBindList != null) {
       for (int i = varBindList.length - 1; i >= 0; i--) {
         SnmpVarBind bind = varBindList[i];
         if (bind != null) {
           benc.openSequence();
           encodeVarBindValue(benc, bind.value);
           benc.putOid(bind.oid.longValue());
           benc.closeSequence();
           encodedVarBindCount++;
         }
       }
     }
     benc.closeSequence();
   } catch (ArrayIndexOutOfBoundsException x) {
     throw new SnmpTooBigException(encodedVarBindCount);
   }
 }
Esempio n. 2
0
 /**
  * Generate LDAPResult
  *
  * @param dn Distinguished Name
  * @param resultProtocol Result protocol/operation code
  * @param resultCode Result code
  * @param errMsg Error Message
  * @return reponse
  */
 private void generateResult(String dn, int resultProtocol, int resultCode, String errMsg) {
   try {
     m_encoder.beginSeq(48); // Hard coded here for Envelope header
     m_encoder.encodeInt(m_ldapMsg.getMsgId());
     m_encoder.beginSeq(resultProtocol);
     m_encoder.encodeInt(resultCode, 10); // Enumeration - 10
     // Adding LDAPDN
     m_encoder.encodeString(dn, true);
     // Adding error message
     m_encoder.encodeString(errMsg == null ? "" : errMsg, true);
     m_encoder.endSeq();
     m_encoder.endSeq();
     log.fine(
         "#"
             + m_ldapMsg.getMsgId()
             + ": "
             + "dn="
             + dn
             + ", op="
             + resultProtocol
             + ", result="
             + resultCode
             + ", errMsg="
             + errMsg);
   } catch (Exception ex) {
     log.log(Level.SEVERE, "", ex);
   }
 } // generateResult
Esempio n. 3
0
  /**
   * Encodes this message and puts the result in the specified byte array. For internal use only.
   *
   * @param outputBytes An array to receive the resulting encoding.
   * @exception ArrayIndexOutOfBoundsException If the result does not fit into the specified array.
   */
  public int encodeMessage(byte[] outputBytes) throws SnmpTooBigException {
    int encodingLength = 0;
    if (data == null) throw new IllegalArgumentException("Data field is null");

    //
    // Reminder: BerEncoder does backward encoding !
    //
    try {
      BerEncoder benc = new BerEncoder(outputBytes);
      benc.openSequence();
      benc.putAny(data, dataLength);
      benc.putOctetString((community != null) ? community : new byte[0]);
      benc.putInteger(version);
      benc.closeSequence();
      encodingLength = benc.trim();
    } catch (ArrayIndexOutOfBoundsException x) {
      throw new SnmpTooBigException();
    }

    return encodingLength;
  }
Esempio n. 4
0
 /** For SNMP Runtime private use only. */
 void encodeVarBindValue(BerEncoder benc, SnmpValue v) throws SnmpStatusException {
   if (v == null) {
     benc.putNull();
   } else if (v instanceof SnmpIpAddress) {
     benc.putOctetString(((SnmpIpAddress) v).byteValue(), SnmpValue.IpAddressTag);
   } else if (v instanceof SnmpCounter) {
     benc.putInteger(((SnmpCounter) v).longValue(), SnmpValue.CounterTag);
   } else if (v instanceof SnmpGauge) {
     benc.putInteger(((SnmpGauge) v).longValue(), SnmpValue.GaugeTag);
   } else if (v instanceof SnmpTimeticks) {
     benc.putInteger(((SnmpTimeticks) v).longValue(), SnmpValue.TimeticksTag);
   } else if (v instanceof SnmpOpaque) {
     benc.putOctetString(((SnmpOpaque) v).byteValue(), SnmpValue.OpaqueTag);
   } else if (v instanceof SnmpInt) {
     benc.putInteger(((SnmpInt) v).intValue());
   } else if (v instanceof SnmpString) {
     benc.putOctetString(((SnmpString) v).byteValue());
   } else if (v instanceof SnmpOid) {
     benc.putOid(((SnmpOid) v).longValue());
   } else if (v instanceof SnmpCounter64) {
     if (version == snmpVersionOne) {
       throw new SnmpStatusException("Invalid value for SNMP v1 : " + v);
     }
     benc.putInteger(((SnmpCounter64) v).longValue(), SnmpValue.Counter64Tag);
   } else if (v instanceof SnmpNull) {
     int tag = ((SnmpNull) v).getTag();
     if ((version == snmpVersionOne) && (tag != SnmpValue.NullTag)) {
       throw new SnmpStatusException("Invalid value for SNMP v1 : " + v);
     }
     if ((version == snmpVersionTwo)
         && (tag != SnmpValue.NullTag)
         && (tag != SnmpVarBind.errNoSuchObjectTag)
         && (tag != SnmpVarBind.errNoSuchInstanceTag)
         && (tag != SnmpVarBind.errEndOfMibViewTag)) {
       throw new SnmpStatusException("Invalid value " + v);
     }
     benc.putNull(tag);
   } else {
     throw new SnmpStatusException("Invalid value " + v);
   }
 }
Esempio n. 5
0
  /**
   * Initializes this message with the specified <CODE>pdu</CODE>.
   *
   * <p>This method initializes the data field with an array of <CODE>maxDataLength</CODE> bytes. It
   * encodes the <CODE>pdu</CODE>. The resulting encoding is stored in the data field and the length
   * of the encoding is stored in <CODE>dataLength</CODE>.
   *
   * <p>If the encoding length exceeds <CODE>maxDataLength</CODE>, the method throws an exception.
   *
   * @param pdu The PDU to be encoded.
   * @param maxDataLength The maximum length permitted for the data field.
   * @exception SnmpStatusException If the specified <CODE>pdu</CODE> is not valid.
   * @exception SnmpTooBigException If the resulting encoding does not fit into <CODE>maxDataLength
   *     </CODE> bytes.
   * @exception ArrayIndexOutOfBoundsException If the encoding exceeds <CODE>maxDataLength</CODE>.
   * @since 1.5
   */
  public void encodeSnmpPdu(SnmpPdu pdu, int maxDataLength)
      throws SnmpStatusException, SnmpTooBigException {
    //
    // The easy work
    //
    SnmpPduPacket pdupacket = (SnmpPduPacket) pdu;
    version = pdupacket.version;
    community = pdupacket.community;
    address = pdupacket.address;
    port = pdupacket.port;

    //
    // Allocate the array to receive the encoding.
    //
    data = new byte[maxDataLength];

    //
    // Encode the pdupacket
    // Reminder: BerEncoder does backward encoding !
    //

    try {
      BerEncoder benc = new BerEncoder(data);
      benc.openSequence();
      encodeVarBindList(benc, pdupacket.varBindList);

      switch (pdupacket.type) {
        case pduGetRequestPdu:
        case pduGetNextRequestPdu:
        case pduInformRequestPdu:
        case pduGetResponsePdu:
        case pduSetRequestPdu:
        case pduV2TrapPdu:
        case pduReportPdu:
          SnmpPduRequest reqPdu = (SnmpPduRequest) pdupacket;
          benc.putInteger(reqPdu.errorIndex);
          benc.putInteger(reqPdu.errorStatus);
          benc.putInteger(reqPdu.requestId);
          break;

        case pduGetBulkRequestPdu:
          SnmpPduBulk bulkPdu = (SnmpPduBulk) pdupacket;
          benc.putInteger(bulkPdu.maxRepetitions);
          benc.putInteger(bulkPdu.nonRepeaters);
          benc.putInteger(bulkPdu.requestId);
          break;

        case pduV1TrapPdu:
          SnmpPduTrap trapPdu = (SnmpPduTrap) pdupacket;
          benc.putInteger(trapPdu.timeStamp, SnmpValue.TimeticksTag);
          benc.putInteger(trapPdu.specificTrap);
          benc.putInteger(trapPdu.genericTrap);
          if (trapPdu.agentAddr != null)
            benc.putOctetString(trapPdu.agentAddr.byteValue(), SnmpValue.IpAddressTag);
          else benc.putOctetString(new byte[0], SnmpValue.IpAddressTag);
          benc.putOid(trapPdu.enterprise.longValue());
          break;

        default:
          throw new SnmpStatusException("Invalid pdu type " + String.valueOf(pdupacket.type));
      }
      benc.closeSequence(pdupacket.type);
      dataLength = benc.trim();
    } catch (ArrayIndexOutOfBoundsException x) {
      throw new SnmpTooBigException();
    }
  }
Esempio n. 6
0
  /**
   * Get the response according to the request message
   *
   * @param model model
   * @param remoteHost remote host name
   * @param remoteAddr remote host ip address
   * @return response
   */
  public byte[] getResult(MLdapProcessor model, String remoteHost, String remoteAddr) {
    if (m_errNo != LDAP_SUCCESS) {
      generateResult(
          "",
          (m_ldapMsg.getOperation() == LdapMessage.BIND_REQUEST
              ? LdapMessage.BIND_RESPONSE
              : LdapMessage.SEARCH_RES_RESULT),
          m_errNo,
          ldapErrorMessage[m_errNo] + ": " + m_errStr);
      m_encoder.getTrimmedBuf();
    }

    try {
      String usrId = m_ldapMsg.getUserId();
      String o = m_ldapMsg.getOrg();
      String ou = m_ldapMsg.getOrgUnit();
      int msgId = m_ldapMsg.getMsgId();

      // Adding the Application 1 Sequence
      if (m_ldapMsg.getOperation() == LdapMessage.BIND_REQUEST) {
        String pwd = m_ldapMsg.getUserPasswd();
        if (pwd == null || pwd.length() <= 0) {
          // 1st anonymous bind
          generateResult(m_ldapMsg.getDN(), LdapMessage.BIND_RESPONSE, LDAP_SUCCESS, null);
          log.config("#" + msgId + ": Success on anonymous bind");
          return m_encoder.getTrimmedBuf();
        }

        // Authenticate with Compiere data
        if (m_ldapUser.getUserId()
            == null) { // Try to authenticate on the 1st bind, must be java client
          m_ldapUser.reset();
          model.authenticate(m_ldapUser, usrId, o, ou, remoteHost, remoteAddr);
          if (m_ldapUser.getErrorMsg() != null) { // Failed to authenticated with compiere
            m_errNo = LDAP_NO_SUCH_OBJECT;
            generateResult(
                m_ldapMsg.getBaseObj(),
                LdapMessage.SEARCH_RES_RESULT,
                LDAP_NO_SUCH_OBJECT,
                ldapErrorMessage[LDAP_NO_SUCH_OBJECT] + m_ldapUser.getErrorMsg());
            log.config("#" + msgId + ": Failed with bind");
            return m_encoder.getTrimmedBuf();
          }
        }

        // Check to see if the input passwd is match to the one
        // in compiere database
        if (m_ldapUser.getUserId() != null
            && m_ldapUser.getPassword() != null
            && usrId.compareTo(m_ldapUser.getUserId()) == 0
            && !SecureEngine.isEncrypted(pwd)
            && (pwd.compareTo(m_ldapUser.getPassword()) == 0
                || pwd.compareTo(SecureEngine.decrypt(m_ldapUser.getPassword()))
                    == 0)) { // Successfully authenticated
          generateResult("", LdapMessage.BIND_RESPONSE, LDAP_SUCCESS, null);
          // Close the connection to client since most of the client
          // application might cache the connection but we can't afford
          // to have too many such client connection
          m_disconnect = true;
          log.config("#" + msgId + ": Success authenticate with password");
        } else { // Unsuccessfully authenticated
          m_errNo = LDAP_INAPPROPRIATE_AUTHENTICATION;
          generateResult(
              "",
              LdapMessage.BIND_RESPONSE,
              LDAP_INAPPROPRIATE_AUTHENTICATION,
              ldapErrorMessage[LDAP_INAPPROPRIATE_AUTHENTICATION]);
          log.info(
              "#" + msgId + ": Failed : " + ldapErrorMessage[LDAP_INAPPROPRIATE_AUTHENTICATION]);
        }
      } else if (m_ldapMsg.getOperation() == LdapMessage.SEARCH_REQUEST) {
        // Authenticate with compiere database
        m_ldapUser.reset();
        model.authenticate(m_ldapUser, usrId, o, ou, remoteHost, remoteAddr);
        if (m_ldapUser.getErrorMsg() != null) {
          m_errNo = LDAP_NO_SUCH_OBJECT;
          generateResult(
              m_ldapMsg.getBaseObj(),
              LdapMessage.SEARCH_RES_RESULT,
              LDAP_NO_SUCH_OBJECT,
              ldapErrorMessage[LDAP_NO_SUCH_OBJECT] + m_ldapUser.getErrorMsg());
          log.info("#" + msgId + ": Failed with SEARCH_REQUEST");
          return m_encoder.getTrimmedBuf();
        }

        m_encoder.beginSeq(48); // Hard coded here for Envelope header
        m_encoder.encodeInt(msgId);
        m_encoder.beginSeq(LdapMessage.SEARCH_REP_ENTRY); // Application 4
        m_encoder.encodeString("cn=" + m_ldapMsg.getUserId(), true); // this should be object name
        // not going to put in any attributes for this
        m_encoder.beginSeq(48);
        m_encoder.endSeq();
        m_encoder.endSeq();
        m_encoder.endSeq();

        // SearchResultDone Application 5 for bind
        // Result 0 = success
        // No error message
        generateResult(m_ldapMsg.getBaseObj(), LdapMessage.SEARCH_RES_RESULT, LDAP_SUCCESS, null);
        log.config("#" + msgId + ": Success with SEARCH_REQUEST");
      }

      return m_encoder.getTrimmedBuf();
    } catch (Exception e) {
      log.log(Level.SEVERE, "", e);

      // Get the response operation
      int responseOp = LdapMessage.BIND_RESPONSE;
      if (m_ldapMsg.getOperation() == LdapMessage.SEARCH_REQUEST)
        responseOp = LdapMessage.SEARCH_RES_RESULT;

      // Send the response to the client and disconnect
      m_errNo = LDAP_OTHER;
      generateResult(
          m_ldapMsg.getBaseObj(),
          responseOp,
          LDAP_OTHER,
          ldapErrorMessage[LDAP_OTHER] + e.getMessage());
      m_disconnect = true;
    }

    return m_encoder.getTrimmedBuf();
  } //	getResult