Search in sources :

Example 71 with ASN1StreamReader

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

the class SearchResultEntry method readSearchEntryFrom.

/**
 * Creates a new search result entry object with the protocol op and controls
 * read from the given ASN.1 stream reader.
 *
 * @param  messageID        The message ID for the LDAP message containing
 *                          this response.
 * @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.
 * @param  schema           The schema to use to select the appropriate
 *                          matching rule to use for each attribute.  It may
 *                          be {@code null} if the default matching rule
 *                          should always be used.
 *
 * @return  The decoded search result entry object.
 *
 * @throws  LDAPException  If a problem occurs while reading or decoding data
 *                         from the ASN.1 stream reader.
 */
@NotNull()
static SearchResultEntry readSearchEntryFrom(final int messageID, @NotNull final ASN1StreamReaderSequence messageSequence, @NotNull final ASN1StreamReader reader, @Nullable final Schema schema) throws LDAPException {
    try {
        reader.beginSequence();
        final String dn = reader.readString();
        final ArrayList<Attribute> attrList = new ArrayList<>(10);
        final ASN1StreamReaderSequence attrSequence = reader.beginSequence();
        while (attrSequence.hasMoreElements()) {
            attrList.add(Attribute.readFrom(reader, schema));
        }
        Control[] controls = NO_CONTROLS;
        if (messageSequence.hasMoreElements()) {
            final ArrayList<Control> controlList = new ArrayList<>(5);
            final ASN1StreamReaderSequence controlSequence = reader.beginSequence();
            while (controlSequence.hasMoreElements()) {
                controlList.add(Control.readFrom(reader));
            }
            controls = new Control[controlList.size()];
            controlList.toArray(controls);
        }
        return new SearchResultEntry(messageID, dn, schema, attrList, controls);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        throw le;
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_SEARCH_ENTRY_CANNOT_DECODE.get(StaticUtils.getExceptionMessage(e)), e);
    }
}
Also used : ASN1StreamReaderSequence(com.unboundid.asn1.ASN1StreamReaderSequence) ArrayList(java.util.ArrayList) NotNull(com.unboundid.util.NotNull)

Example 72 with ASN1StreamReader

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

the class SearchResultReference method readSearchReferenceFrom.

/**
 * Creates a new search result reference object with the protocol op and
 * controls read from the given ASN.1 stream reader.
 *
 * @param  messageID        The message ID for the LDAP message containing
 *                          this response.
 * @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 search result reference object.
 *
 * @throws  LDAPException  If a problem occurs while reading or decoding data
 *                         from the ASN.1 stream reader.
 */
@NotNull()
static SearchResultReference readSearchReferenceFrom(final int messageID, @NotNull final ASN1StreamReaderSequence messageSequence, @NotNull final ASN1StreamReader reader) throws LDAPException {
    try {
        final ArrayList<String> refList = new ArrayList<>(5);
        final ASN1StreamReaderSequence refSequence = reader.beginSequence();
        while (refSequence.hasMoreElements()) {
            refList.add(reader.readString());
        }
        final String[] referralURLs = new String[refList.size()];
        refList.toArray(referralURLs);
        Control[] controls = NO_CONTROLS;
        if (messageSequence.hasMoreElements()) {
            final ArrayList<Control> controlList = new ArrayList<>(5);
            final ASN1StreamReaderSequence controlSequence = reader.beginSequence();
            while (controlSequence.hasMoreElements()) {
                controlList.add(Control.readFrom(reader));
            }
            controls = new Control[controlList.size()];
            controlList.toArray(controls);
        }
        return new SearchResultReference(messageID, referralURLs, controls);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        throw le;
    } catch (final Exception e) {
        Debug.debugException(e);
        throw new LDAPException(ResultCode.DECODING_ERROR, ERR_SEARCH_REFERENCE_CANNOT_DECODE.get(StaticUtils.getExceptionMessage(e)), e);
    }
}
Also used : ASN1StreamReaderSequence(com.unboundid.asn1.ASN1StreamReaderSequence) ArrayList(java.util.ArrayList) NotNull(com.unboundid.util.NotNull)

Example 73 with ASN1StreamReader

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

the class ManageCertificatesServerCertificateCollector method run.

/**
 * Performs the core processing for this thread.  It will establish a TCP
 * connection to the specified server, optionally perform the LDAP StartTLS
 * operation, and initiate TLS negotiation so that the server's certificate
 * chain can be
 */
@Override()
public void run() {
    // Establish a non-secure connection to the target server.
    final String hostPort = hostname + ':' + port;
    if (verbose) {
        manageCertificates.wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CERT_COLLECTOR_CONNECTING.get(hostPort));
    }
    final Socket nonSecureSocket;
    try {
        nonSecureSocket = new Socket();
        final InetAddress address = LDAPConnectionOptions.DEFAULT_NAME_RESOLVER.getByName(hostname);
        nonSecureSocket.connect(new InetSocketAddress(address, port), 60_000);
        if (verbose) {
            manageCertificates.wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CERT_COLLECTOR_CONNECTED.get());
        }
    } catch (final Exception e) {
        Debug.debugException(e);
        final String message = ERR_MANAGE_CERTS_CERT_COLLECTOR_CONNECT_FAILED.get(hostPort);
        manageCertificates.err();
        manageCertificates.wrapErr(0, WRAP_COLUMN, message);
        e.printStackTrace(manageCertificates.getErr());
        queue.offer(new CertException(message, e));
        return;
    }
    try {
        // If we should send an LDAP StartTLS extended request, then do that now.
        if (useLDAPStartTLS) {
            if (verbose) {
                manageCertificates.out();
                manageCertificates.wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CERT_COLLECTOR_SENDING_START_TLS.get());
            }
            final LDAPMessage startTLSRequestMessage = new LDAPMessage(1, new ExtendedRequestProtocolOp(StartTLSExtendedRequest.STARTTLS_REQUEST_OID, null));
            try {
                nonSecureSocket.getOutputStream().write(startTLSRequestMessage.encode().encode());
                nonSecureSocket.getOutputStream().flush();
                final ASN1StreamReader asn1Reader = new ASN1StreamReader(nonSecureSocket.getInputStream());
                final LDAPMessage startTLSResponseMessage = LDAPMessage.readFrom(asn1Reader, true);
                if (startTLSResponseMessage == null) {
                    // This could happen if the server terminated the connection for
                    // some reason (e.g., it's not an LDAP server, or the user specified
                    // an already-secure port).
                    final String message = ERR_MANAGE_CERTS_CERT_COLLECTOR_START_TLS_FAILED.get();
                    manageCertificates.wrapErr(0, WRAP_COLUMN, message);
                    queue.offer(new CertException(message));
                    return;
                }
                final ExtendedResponseProtocolOp startTLSResponse = startTLSResponseMessage.getExtendedResponseProtocolOp();
                if (startTLSResponse.getResultCode() == ResultCode.SUCCESS_INT_VALUE) {
                    if (verbose) {
                        manageCertificates.wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CERT_COLLECTOR_START_TLS_SUCCESSFUL.get());
                    }
                } else {
                    final String message = ERR_MANAGE_CERTS_CERT_COLLECTOR_START_TLS_FAILED.get();
                    manageCertificates.wrapErr(0, WRAP_COLUMN, message);
                    final String[] referralURLArray = startTLSResponse.getReferralURLs().toArray(StaticUtils.NO_STRINGS);
                    final Control[] responseControlArray = startTLSResponseMessage.getControls().toArray(StaticUtils.NO_CONTROLS);
                    final ExtendedResult extendedResult = new ExtendedResult(startTLSRequestMessage.getMessageID(), ResultCode.valueOf(startTLSResponse.getResultCode()), startTLSResponse.getDiagnosticMessage(), startTLSResponse.getMatchedDN(), referralURLArray, startTLSResponse.getResponseOID(), startTLSResponse.getResponseValue(), responseControlArray);
                    for (final String line : ResultUtils.formatResult(extendedResult, false, 0, WRAP_COLUMN)) {
                        manageCertificates.err(line);
                    }
                    queue.offer(new CertException(message));
                    return;
                }
            } catch (final Exception e) {
                final String message = ERR_MANAGE_CERTS_CERT_COLLECTOR_START_TLS_FAILED.get();
                manageCertificates.wrapErr(0, WRAP_COLUMN, message);
                e.printStackTrace(manageCertificates.getErr());
                queue.offer(new CertException(message));
                return;
            }
        }
        // Convert the non-secure Socket to an SSLSocket and begin TLS
        // negotiation.
        final SSLSocket sslSocket;
        try {
            if (verbose) {
                manageCertificates.out();
                manageCertificates.wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CERT_COLLECTOR_BEGINNING_TLS_NEGOTIATION.get());
            }
            final SSLUtil sslUtil = new SSLUtil(this);
            sslSocket = (SSLSocket) sslUtil.createSSLSocketFactory().createSocket(nonSecureSocket, hostname, port, true);
            sslSocket.startHandshake();
            sslSocket.setSoTimeout(1000);
        } catch (final Exception e) {
            Debug.debugException(e);
            final String message = ERR_MANAGE_CERTS_CERT_COLLECTOR_ERROR_STARTING_TLS_NEGOTIATION.get();
            manageCertificates.wrapErr(0, WRAP_COLUMN, message);
            e.printStackTrace(manageCertificates.getErr());
            queue.offer(new CertException(message, e));
            return;
        }
        try {
            final long stopWaitingTime = System.currentTimeMillis() + 60_000L;
            while ((System.currentTimeMillis() < stopWaitingTime) && (!gotCertificateChain)) {
                try {
                    final int bytesRead = sslSocket.getInputStream().read();
                    if ((bytesRead < 0) && gotCertificateChain) {
                        // to the queue, so we don't need to add anything here.
                        return;
                    }
                } catch (final Exception e) {
                    Debug.debugException(e);
                }
            }
            if (!gotCertificateChain) {
                // If we have gotten here, then it should mean that we timed out
                // without having gotten the certificate chain.
                final String message = ERR_MANAGE_CERTS_CERT_COLLECTOR_NO_CERT_CHAIN_RECEIVED.get(hostPort);
                manageCertificates.wrapErr(0, WRAP_COLUMN, message);
                queue.offer(new CertException(message));
                return;
            }
            if (verbose) {
                final SSLSession sslSession = sslSocket.getSession();
                final String negotiatedProtocol = sslSession.getProtocol();
                if (negotiatedProtocol != null) {
                    manageCertificates.wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CERT_COLLECTOR_NEGOTIATED_TLS_PROTOCOL.get(negotiatedProtocol));
                }
                final String negotiatedCipherSuite = sslSession.getCipherSuite();
                if (negotiatedCipherSuite != null) {
                    manageCertificates.wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CERT_COLLECTOR_NEGOTIATED_TLS_SUITE.get(negotiatedCipherSuite));
                }
            }
        } finally {
            try {
                sslSocket.close();
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        }
    } finally {
        try {
            nonSecureSocket.close();
        } catch (final Exception e) {
            Debug.debugException(e);
        }
    }
}
Also used : ExtendedResponseProtocolOp(com.unboundid.ldap.protocol.ExtendedResponseProtocolOp) InetSocketAddress(java.net.InetSocketAddress) SSLSocket(javax.net.ssl.SSLSocket) LDAPMessage(com.unboundid.ldap.protocol.LDAPMessage) SSLSession(javax.net.ssl.SSLSession) CertificateException(java.security.cert.CertificateException) ExtendedRequestProtocolOp(com.unboundid.ldap.protocol.ExtendedRequestProtocolOp) SSLUtil(com.unboundid.util.ssl.SSLUtil) Control(com.unboundid.ldap.sdk.Control) ExtendedResult(com.unboundid.ldap.sdk.ExtendedResult) InetAddress(java.net.InetAddress) ASN1StreamReader(com.unboundid.asn1.ASN1StreamReader) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket)

Example 74 with ASN1StreamReader

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

the class SearchRequestProtocolOpTestCase method testSearchRequestProtocolOp.

/**
 * Provides test coverage for the search request protocol op.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test()
public void testSearchRequestProtocolOp() throws Exception {
    LinkedList<String> attrs = new LinkedList<String>();
    attrs.add("*");
    attrs.add("+");
    SearchRequestProtocolOp op = new SearchRequestProtocolOp("dc=example,dc=com", SearchScope.SUB, DereferencePolicy.NEVER, 1, 2, false, Filter.createEqualityFilter("uid", "test.user"), attrs);
    ASN1Buffer buffer = new ASN1Buffer();
    op.writeTo(buffer);
    byte[] opBytes = buffer.toByteArray();
    ByteArrayInputStream inputStream = new ByteArrayInputStream(opBytes);
    ASN1StreamReader reader = new ASN1StreamReader(inputStream);
    op = new SearchRequestProtocolOp(reader);
    op = SearchRequestProtocolOp.decodeProtocolOp(op.encodeProtocolOp());
    op = new SearchRequestProtocolOp(op.toSearchRequest());
    assertEquals(new DN(op.getBaseDN()), new DN("dc=example,dc=com"));
    assertEquals(op.getScope(), SearchScope.SUB);
    assertEquals(op.getDerefPolicy(), DereferencePolicy.NEVER);
    assertEquals(op.getSizeLimit(), 1);
    assertEquals(op.getTimeLimit(), 2);
    assertFalse(op.typesOnly());
    assertNotNull(op.getFilter());
    assertEquals(op.getFilter(), Filter.create("(uid=test.user)"));
    assertNotNull(op.getAttributes());
    assertEquals(op.getAttributes().size(), 2);
    assertEquals(op.getProtocolOpType(), (byte) 0x63);
    assertNotNull(op.toString());
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1Buffer(com.unboundid.asn1.ASN1Buffer) DN(com.unboundid.ldap.sdk.DN) ASN1StreamReader(com.unboundid.asn1.ASN1StreamReader) LinkedList(java.util.LinkedList) Test(org.testng.annotations.Test)

Example 75 with ASN1StreamReader

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

the class SearchRequestProtocolOpTestCase method testDecodeMalformedFilter.

/**
 * Tests the behavior when trying to decode a search request with a malformed
 * filter.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test(expectedExceptions = { LDAPException.class })
public void testDecodeMalformedFilter() throws Exception {
    ASN1Buffer b = new ASN1Buffer();
    ASN1BufferSequence s = b.beginSequence((byte) 0x63);
    b.addOctetString("dc=example,dc=com");
    b.addEnumerated(2);
    b.addEnumerated(0);
    b.addInteger(0);
    b.addInteger(0);
    b.addBoolean(false);
    b.addOctetString((byte) 0x00);
    b.beginSequence().end();
    s.end();
    ByteArrayInputStream inputStream = new ByteArrayInputStream(b.toByteArray());
    ASN1StreamReader reader = new ASN1StreamReader(inputStream);
    new SearchRequestProtocolOp(reader);
}
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