Search in sources :

Example 66 with ASN1StreamReader

use of com.unboundid.asn1.ASN1StreamReader in project ldapsdk by pingidentity.

the class CryptoHelper method inferKeyStoreType.

/**
 * Attempts to automatically determine the type of key store that the
 * specified file represents.  This method supports JKS, PKCS #12, and BCFKS
 * key store types.
 *
 * @param  keyStoreFile  The key store file to examine.  It must not be
 *                       {@code null}, and the file must exist.
 *
 * @return  The inferred key store type for the specified key store.
 *
 * @throws  KeyStoreException  If the key store type cannot be inferred.
 */
@NotNull()
public static String inferKeyStoreType(@NotNull final File keyStoreFile) throws KeyStoreException {
    if (!keyStoreFile.exists()) {
        throw new KeyStoreException(ERR_CRYPTO_HELPER_INFER_KS_TYPE_NO_SUCH_FILE.get(keyStoreFile.getAbsolutePath()));
    }
    try (FileInputStream fis = new FileInputStream(keyStoreFile);
        BufferedInputStream bis = new BufferedInputStream(fis)) {
        // Read the first byte from the file.  Set a mark so that we can back up
        // and re-read it if we need to make a more complete determination.
        bis.mark(1);
        final int firstByte = bis.read();
        bis.reset();
        // If the file is empty, then that's an error.
        if (firstByte < 0) {
            throw new KeyStoreException(ERR_CRYPTO_HELPER_INFER_KS_TYPE_EMPTY_FILE.get(keyStoreFile.getAbsolutePath()));
        }
        // JKS key stores should start with 0xFEEDFEED.
        if (firstByte == 0xFE) {
            return KEY_STORE_TYPE_JKS;
        }
        // first element of the sequence will be another sequence.
        if (firstByte == 0x30) {
            try (ASN1StreamReader asn1StreamReader = new ASN1StreamReader(bis)) {
                final ASN1StreamReaderSequence sequenceHeader = asn1StreamReader.beginSequence();
                if (sequenceHeader.hasMoreElements()) {
                    final int firstSequenceElementType = asn1StreamReader.peek();
                    if (firstSequenceElementType == ASN1Constants.UNIVERSAL_INTEGER_TYPE) {
                        final int intValue = asn1StreamReader.readInteger();
                        if (intValue == 3) {
                            return KEY_STORE_TYPE_PKCS_12;
                        }
                    } else if (firstSequenceElementType == ASN1Constants.UNIVERSAL_SEQUENCE_TYPE) {
                        return KEY_STORE_TYPE_BCFKS;
                    }
                }
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        }
        // If we've gotten here, then we can't infer the key store type.
        throw new KeyStoreException(ERR_CRYPTO_HELPER_INFER_KS_TYPE_UNRECOGNIZED.get(keyStoreFile.getAbsolutePath()));
    } catch (final KeyStoreException e) {
        Debug.debugException(e);
        throw e;
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new KeyStoreException(ERR_CRYPTO_HELPER_INFER_KS_TYPE_READ_ERROR.get(keyStoreFile.getAbsolutePath(), StaticUtils.getExceptionMessage(e)), e);
    }
}
Also used : ASN1StreamReaderSequence(com.unboundid.asn1.ASN1StreamReaderSequence) BufferedInputStream(java.io.BufferedInputStream) KeyStoreException(java.security.KeyStoreException) ASN1StreamReader(com.unboundid.asn1.ASN1StreamReader) FileInputStream(java.io.FileInputStream) KeyStoreException(java.security.KeyStoreException) LDAPRuntimeException(com.unboundid.ldap.sdk.LDAPRuntimeException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) LDAPException(com.unboundid.ldap.sdk.LDAPException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 67 with ASN1StreamReader

use of com.unboundid.asn1.ASN1StreamReader in project ldapsdk by pingidentity.

the class BindResult method readBindResultFrom.

/**
 * Creates a new bind result object with the provided message ID and with the
 * protocol op and controls read from the given ASN.1 stream reader.
 *
 * @param  messageID        The LDAP message ID for the LDAP message that is
 *                          associated with this bind result.
 * @param  messageSequence  The ASN.1 stream reader sequence used in the
 *                          course of reading the LDAP message elements.
 * @param  reader           The ASN.1 stream reader from which to read the
 *                          protocol op and controls.
 *
 * @return  The decoded bind result.
 *
 * @throws  LDAPException  If a problem occurs while reading or decoding data
 *                         from the ASN.1 stream reader.
 */
@NotNull()
static BindResult readBindResultFrom(final int messageID, @NotNull final ASN1StreamReaderSequence messageSequence, @NotNull final ASN1StreamReader reader) throws LDAPException {
    try {
        final ASN1StreamReaderSequence protocolOpSequence = reader.beginSequence();
        final ResultCode resultCode = ResultCode.valueOf(reader.readEnumerated());
        String matchedDN = reader.readString();
        if (matchedDN.isEmpty()) {
            matchedDN = null;
        }
        String diagnosticMessage = reader.readString();
        if (diagnosticMessage.isEmpty()) {
            diagnosticMessage = null;
        }
        String[] referralURLs = null;
        ASN1OctetString serverSASLCredentials = null;
        while (protocolOpSequence.hasMoreElements()) {
            final byte type = (byte) reader.peek();
            switch(type) {
                case TYPE_REFERRAL_URLS:
                    final ArrayList<String> refList = new ArrayList<>(1);
                    final ASN1StreamReaderSequence refSequence = reader.beginSequence();
                    while (refSequence.hasMoreElements()) {
                        refList.add(reader.readString());
                    }
                    referralURLs = new String[refList.size()];
                    refList.toArray(referralURLs);
                    break;
                case TYPE_SERVER_SASL_CREDENTIALS:
                    serverSASLCredentials = new ASN1OctetString(type, reader.readBytes());
                    break;
                default:
                    throw new LDAPException(ResultCode.DECODING_ERROR, ERR_BIND_RESULT_INVALID_ELEMENT.get(StaticUtils.toHex(type)));
            }
        }
        Control[] controls = NO_CONTROLS;
        if (messageSequence.hasMoreElements()) {
            final ArrayList<Control> controlList = new ArrayList<>(1);
            final ASN1StreamReaderSequence controlSequence = reader.beginSequence();
            while (controlSequence.hasMoreElements()) {
                controlList.add(Control.readFrom(reader));
            }
            controls = new Control[controlList.size()];
            controlList.toArray(controls);
        }
        return new BindResult(messageID, resultCode, diagnosticMessage, matchedDN, referralURLs, controls, serverSASLCredentials);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        throw le;
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_BIND_RESULT_CANNOT_DECODE.get(StaticUtils.getExceptionMessage(e)), e);
    }
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) ASN1StreamReaderSequence(com.unboundid.asn1.ASN1StreamReaderSequence) ArrayList(java.util.ArrayList) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) NotNull(com.unboundid.util.NotNull)

Example 68 with ASN1StreamReader

use of com.unboundid.asn1.ASN1StreamReader in project ldapsdk by pingidentity.

the class LDAPMessage method readLDAPResponseFrom.

/**
 * Reads {@link LDAPResponse} object from the provided ASN.1 stream reader.
 *
 * @param  reader               The ASN.1 stream reader from which the LDAP
 *                              message should be read.
 * @param  ignoreSocketTimeout  Indicates whether to ignore socket timeout
 *                              exceptions caught during processing.  This
 *                              should be {@code true} when the associated
 *                              connection is operating in asynchronous mode,
 *                              and {@code false} when operating in
 *                              synchronous mode.  In either case, exceptions
 *                              will not be ignored for the first read, since
 *                              that will be handled by the connection reader.
 * @param  schema               The schema to use to select the appropriate
 *                              matching rule for attributes included in the
 *                              response.
 *
 * @return  The decoded LDAP message, or {@code null} if the end of the input
 *          stream has been reached.
 *
 * @throws  LDAPException  If an error occurs while attempting to read or
 *                         decode the LDAP message.
 */
@Nullable()
public static LDAPResponse readLDAPResponseFrom(@NotNull final ASN1StreamReader reader, final boolean ignoreSocketTimeout, @Nullable final Schema schema) throws LDAPException {
    final ASN1StreamReaderSequence messageSequence;
    try {
        reader.setIgnoreSocketTimeout(false, ignoreSocketTimeout);
        messageSequence = reader.beginSequence();
        if (messageSequence == null) {
            return null;
        }
    } catch (final IOException ioe) {
        final ResultCode resultCode;
        if (ioe instanceof SocketTimeoutException) {
            resultCode = ResultCode.TIMEOUT;
        } else {
            Debug.debugException(ioe);
            resultCode = ResultCode.SERVER_DOWN;
        }
        throw new LDAPException(resultCode, ERR_MESSAGE_IO_ERROR.get(StaticUtils.getExceptionMessage(ioe)), ioe);
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MESSAGE_CANNOT_DECODE.get(StaticUtils.getExceptionMessage(e)), e);
    }
    try {
        reader.setIgnoreSocketTimeout(ignoreSocketTimeout, ignoreSocketTimeout);
        final int messageID = reader.readInteger();
        final byte protocolOpType = (byte) reader.peek();
        switch(protocolOpType) {
            case PROTOCOL_OP_TYPE_ADD_RESPONSE:
            case PROTOCOL_OP_TYPE_DELETE_RESPONSE:
            case PROTOCOL_OP_TYPE_MODIFY_RESPONSE:
            case PROTOCOL_OP_TYPE_MODIFY_DN_RESPONSE:
                return InternalSDKHelper.readLDAPResultFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_BIND_RESPONSE:
                return InternalSDKHelper.readBindResultFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_COMPARE_RESPONSE:
                return InternalSDKHelper.readCompareResultFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_EXTENDED_RESPONSE:
                return InternalSDKHelper.readExtendedResultFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_SEARCH_RESULT_ENTRY:
                return InternalSDKHelper.readSearchResultEntryFrom(messageID, messageSequence, reader, schema);
            case PROTOCOL_OP_TYPE_SEARCH_RESULT_REFERENCE:
                return InternalSDKHelper.readSearchResultReferenceFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_SEARCH_RESULT_DONE:
                return InternalSDKHelper.readSearchResultFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_INTERMEDIATE_RESPONSE:
                return InternalSDKHelper.readIntermediateResponseFrom(messageID, messageSequence, reader);
            case PROTOCOL_OP_TYPE_ABANDON_REQUEST:
            case PROTOCOL_OP_TYPE_ADD_REQUEST:
            case PROTOCOL_OP_TYPE_BIND_REQUEST:
            case PROTOCOL_OP_TYPE_COMPARE_REQUEST:
            case PROTOCOL_OP_TYPE_DELETE_REQUEST:
            case PROTOCOL_OP_TYPE_EXTENDED_REQUEST:
            case PROTOCOL_OP_TYPE_MODIFY_REQUEST:
            case PROTOCOL_OP_TYPE_MODIFY_DN_REQUEST:
            case PROTOCOL_OP_TYPE_SEARCH_REQUEST:
            case PROTOCOL_OP_TYPE_UNBIND_REQUEST:
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MESSAGE_PROTOCOL_OP_TYPE_NOT_RESPONSE.get(StaticUtils.toHex(protocolOpType)));
            default:
                throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MESSAGE_INVALID_PROTOCOL_OP_TYPE.get(StaticUtils.toHex(protocolOpType)));
        }
    } catch (final LDAPException le) {
        Debug.debugException(le);
        throw le;
    } catch (final IOException ioe) {
        Debug.debugException(ioe);
        if ((ioe instanceof SocketTimeoutException) || (ioe instanceof InterruptedIOException)) {
            // connection to be terminated.
            throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MESSAGE_CANNOT_DECODE.get(StaticUtils.getExceptionMessage(ioe)));
        } else {
            throw new LDAPException(ResultCode.SERVER_DOWN, ERR_MESSAGE_IO_ERROR.get(StaticUtils.getExceptionMessage(ioe)), ioe);
        }
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_MESSAGE_CANNOT_DECODE.get(StaticUtils.getExceptionMessage(e)), e);
    }
}
Also used : ASN1StreamReaderSequence(com.unboundid.asn1.ASN1StreamReaderSequence) InterruptedIOException(java.io.InterruptedIOException) SocketTimeoutException(java.net.SocketTimeoutException) LDAPException(com.unboundid.ldap.sdk.LDAPException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ResultCode(com.unboundid.ldap.sdk.ResultCode) InterruptedIOException(java.io.InterruptedIOException) SocketTimeoutException(java.net.SocketTimeoutException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) Nullable(com.unboundid.util.Nullable)

Example 69 with ASN1StreamReader

use of com.unboundid.asn1.ASN1StreamReader in project ldapsdk by pingidentity.

the class BindResultTestCase method testReadBindResultFromTooShort.

/**
 * Tests the {@code readBindResultFrom} method with an element containing
 * a response sequence that is too short.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test(expectedExceptions = { LDAPException.class })
public void testReadBindResultFromTooShort() throws Exception {
    ASN1Buffer b = new ASN1Buffer();
    ASN1BufferSequence msgSequence = b.beginSequence();
    b.addInteger(1);
    ASN1BufferSequence opSequence = b.beginSequence(LDAPMessage.PROTOCOL_OP_TYPE_BIND_RESPONSE);
    b.addEnumerated(0);
    opSequence.end();
    msgSequence.end();
    ByteArrayInputStream inputStream = new ByteArrayInputStream(b.toByteArray());
    ASN1StreamReader reader = new ASN1StreamReader(inputStream);
    LDAPMessage.readLDAPResponseFrom(reader, true);
}
Also used : ASN1BufferSequence(com.unboundid.asn1.ASN1BufferSequence) ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1Buffer(com.unboundid.asn1.ASN1Buffer) ASN1StreamReader(com.unboundid.asn1.ASN1StreamReader) Test(org.testng.annotations.Test)

Example 70 with ASN1StreamReader

use of com.unboundid.asn1.ASN1StreamReader in project ldapsdk by pingidentity.

the class BindResultTestCase method testReadBindResultFromInvalidElementType.

/**
 * Tests the {@code readBindResultFrom} method with a sequence containing an
 * invalid element type.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test(expectedExceptions = { LDAPException.class })
public void testReadBindResultFromInvalidElementType() throws Exception {
    ASN1Buffer b = new ASN1Buffer();
    ASN1BufferSequence msgSequence = b.beginSequence();
    b.addInteger(1);
    ASN1BufferSequence opSequence = b.beginSequence(LDAPMessage.PROTOCOL_OP_TYPE_BIND_RESPONSE);
    b.addEnumerated(0);
    b.addOctetString();
    b.addOctetString();
    b.addOctetString((byte) 0x00);
    opSequence.end();
    msgSequence.end();
    ByteArrayInputStream inputStream = new ByteArrayInputStream(b.toByteArray());
    ASN1StreamReader reader = new ASN1StreamReader(inputStream);
    LDAPMessage.readLDAPResponseFrom(reader, true);
}
Also used : ASN1BufferSequence(com.unboundid.asn1.ASN1BufferSequence) ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1Buffer(com.unboundid.asn1.ASN1Buffer) ASN1StreamReader(com.unboundid.asn1.ASN1StreamReader) Test(org.testng.annotations.Test)

Aggregations

ASN1StreamReader (com.unboundid.asn1.ASN1StreamReader)121 ByteArrayInputStream (java.io.ByteArrayInputStream)114 Test (org.testng.annotations.Test)114 ASN1Buffer (com.unboundid.asn1.ASN1Buffer)91 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)31 LinkedList (java.util.LinkedList)28 ASN1BufferSequence (com.unboundid.asn1.ASN1BufferSequence)22 DN (com.unboundid.ldap.sdk.DN)21 Control (com.unboundid.ldap.sdk.Control)18 NotNull (com.unboundid.util.NotNull)13 ASN1StreamReaderSequence (com.unboundid.asn1.ASN1StreamReaderSequence)11 ArrayList (java.util.ArrayList)10 ASN1Exception (com.unboundid.asn1.ASN1Exception)8 IOException (java.io.IOException)8 LDAPException (com.unboundid.ldap.sdk.LDAPException)5 InterruptedIOException (java.io.InterruptedIOException)5 SocketTimeoutException (java.net.SocketTimeoutException)5 Attribute (com.unboundid.ldap.sdk.Attribute)4 SSLSocket (javax.net.ssl.SSLSocket)4 ASN1Element (com.unboundid.asn1.ASN1Element)3