Search in sources :

Example 51 with LDAPMessage

use of com.unboundid.ldap.protocol.LDAPMessage in project ldapsdk by pingidentity.

the class SimpleBindRequest method process.

/**
 * {@inheritDoc}
 */
@Override()
@NotNull()
protected BindResult process(@NotNull final LDAPConnection connection, final int depth) throws LDAPException {
    // and this should not be allowed, then throw an exception.
    if (password != null) {
        if ((bindDN.getValue().length > 0) && (password.getValue().length == 0) && connection.getConnectionOptions().bindWithDNRequiresPassword()) {
            final LDAPException le = new LDAPException(ResultCode.PARAM_ERROR, ERR_SIMPLE_BIND_DN_WITHOUT_PASSWORD.get());
            Debug.debugCodingError(le);
            throw le;
        }
    }
    if (connection.synchronousMode()) {
        @SuppressWarnings("deprecation") final boolean autoReconnect = connection.getConnectionOptions().autoReconnect();
        return processSync(connection, autoReconnect);
    }
    // Create the LDAP message.
    messageID = connection.nextMessageID();
    final LDAPMessage message = new LDAPMessage(messageID, this, getControls());
    // Register with the connection reader to be notified of responses for the
    // request that we've created.
    connection.registerResponseAcceptor(messageID, this);
    try {
        // Send the request to the server.
        final long responseTimeout = getResponseTimeoutMillis(connection);
        Debug.debugLDAPRequest(Level.INFO, this, messageID, connection);
        final LDAPConnectionLogger logger = connection.getConnectionOptions().getConnectionLogger();
        if (logger != null) {
            logger.logBindRequest(connection, messageID, this);
        }
        final long requestTime = System.nanoTime();
        connection.getConnectionStatistics().incrementNumBindRequests();
        connection.sendMessage(message, responseTimeout);
        // Wait for and process the response.
        final LDAPResponse response;
        try {
            if (responseTimeout > 0) {
                response = responseQueue.poll(responseTimeout, TimeUnit.MILLISECONDS);
            } else {
                response = responseQueue.take();
            }
        } catch (final InterruptedException ie) {
            Debug.debugException(ie);
            Thread.currentThread().interrupt();
            throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_BIND_INTERRUPTED.get(connection.getHostPort()), ie);
        }
        return handleResponse(connection, response, requestTime, false);
    } finally {
        connection.deregisterResponseAcceptor(messageID);
    }
}
Also used : LDAPMessage(com.unboundid.ldap.protocol.LDAPMessage) LDAPResponse(com.unboundid.ldap.protocol.LDAPResponse) NotNull(com.unboundid.util.NotNull)

Example 52 with LDAPMessage

use of com.unboundid.ldap.protocol.LDAPMessage 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 53 with LDAPMessage

use of com.unboundid.ldap.protocol.LDAPMessage in project ldapsdk by pingidentity.

the class LDAPConnectionTestCase method testSendMessageNotConnected.

/**
 * Tests the {@code sendMessage} method with a connection that is not
 * established.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test(expectedExceptions = { LDAPException.class })
public void testSendMessageNotConnected() throws Exception {
    LDAPConnection conn = new LDAPConnection();
    assertFalse(conn.isConnected());
    assertNull(conn.getConnectedAddress());
    assertTrue(conn.getConnectedPort() < 0);
    assertNotNull(conn.toString());
    conn.sendMessage(new LDAPMessage(conn.nextMessageID(), new UnbindRequestProtocolOp()), 10000L);
}
Also used : LDAPMessage(com.unboundid.ldap.protocol.LDAPMessage) UnbindRequestProtocolOp(com.unboundid.ldap.protocol.UnbindRequestProtocolOp) Test(org.testng.annotations.Test)

Example 54 with LDAPMessage

use of com.unboundid.ldap.protocol.LDAPMessage in project ldapsdk by pingidentity.

the class CannedResponseRequestHandlerTestCase method testDefaultConstructor.

/**
 * Tests the behavior of the request handler with the default configuration.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test()
public void testDefaultConstructor() throws Exception {
    final CannedResponseRequestHandler handler = new CannedResponseRequestHandler().newInstance(null);
    LDAPMessage m = handler.processAddRequest(1, new AddRequestProtocolOp("dc=example,dc=com", Arrays.asList(new Attribute("objectClass", "top", "domain"), new Attribute("dc", "example"))), Collections.<Control>emptyList());
    assertNotNull(m);
    assertEquals(m.getMessageID(), 1);
    assertTrue(m.getProtocolOp() instanceof AddResponseProtocolOp);
    assertNotNull(m.getControls());
    assertTrue(m.getControls().isEmpty());
    m = handler.processBindRequest(2, new BindRequestProtocolOp("uid=admin,dc=example,dc=com", "password"), Collections.<Control>emptyList());
    assertNotNull(m);
    assertEquals(m.getMessageID(), 2);
    assertTrue(m.getProtocolOp() instanceof BindResponseProtocolOp);
    assertNotNull(m.getControls());
    assertTrue(m.getControls().isEmpty());
    m = handler.processCompareRequest(3, new CompareRequestProtocolOp("dc=example,dc=com", "objectClass", new ASN1OctetString("top")), Collections.<Control>emptyList());
    assertNotNull(m);
    assertEquals(m.getMessageID(), 3);
    assertTrue(m.getProtocolOp() instanceof CompareResponseProtocolOp);
    assertNotNull(m.getControls());
    assertTrue(m.getControls().isEmpty());
    m = handler.processDeleteRequest(4, new DeleteRequestProtocolOp("dc=example,dc=com"), Collections.<Control>emptyList());
    assertNotNull(m);
    assertEquals(m.getMessageID(), 4);
    assertTrue(m.getProtocolOp() instanceof DeleteResponseProtocolOp);
    assertNotNull(m.getControls());
    assertTrue(m.getControls().isEmpty());
    m = handler.processExtendedRequest(5, new ExtendedRequestProtocolOp("1.2.3.4", null), Collections.<Control>emptyList());
    assertNotNull(m);
    assertEquals(m.getMessageID(), 5);
    assertTrue(m.getProtocolOp() instanceof ExtendedResponseProtocolOp);
    assertNotNull(m.getControls());
    assertTrue(m.getControls().isEmpty());
    m = handler.processModifyRequest(6, new ModifyRequestProtocolOp("dc=example,dc=com", Arrays.asList(new Modification(ModificationType.REPLACE, "description", "foo"))), Collections.<Control>emptyList());
    assertNotNull(m);
    assertEquals(m.getMessageID(), 6);
    assertTrue(m.getProtocolOp() instanceof ModifyResponseProtocolOp);
    assertNotNull(m.getControls());
    assertTrue(m.getControls().isEmpty());
    m = handler.processModifyDNRequest(6, new ModifyDNRequestProtocolOp("ou=People,dc=example,dc=com", "ou=Users", true, null), Collections.<Control>emptyList());
    assertNotNull(m);
    assertEquals(m.getMessageID(), 6);
    assertTrue(m.getProtocolOp() instanceof ModifyDNResponseProtocolOp);
    assertNotNull(m.getControls());
    assertTrue(m.getControls().isEmpty());
    m = handler.processSearchRequest(7, new SearchRequestProtocolOp("dc=example,dc=com", SearchScope.SUB, DereferencePolicy.NEVER, 0, 0, false, Filter.createEqualityFilter("uid", "test"), Arrays.<String>asList()), Collections.<Control>emptyList());
    assertNotNull(m);
    assertEquals(m.getMessageID(), 7);
    assertTrue(m.getProtocolOp() instanceof SearchResultDoneProtocolOp);
    assertNotNull(m.getControls());
    assertTrue(m.getControls().isEmpty());
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) Modification(com.unboundid.ldap.sdk.Modification) ExtendedResponseProtocolOp(com.unboundid.ldap.protocol.ExtendedResponseProtocolOp) Attribute(com.unboundid.ldap.sdk.Attribute) SearchRequestProtocolOp(com.unboundid.ldap.protocol.SearchRequestProtocolOp) AddRequestProtocolOp(com.unboundid.ldap.protocol.AddRequestProtocolOp) CompareRequestProtocolOp(com.unboundid.ldap.protocol.CompareRequestProtocolOp) DeleteResponseProtocolOp(com.unboundid.ldap.protocol.DeleteResponseProtocolOp) LDAPMessage(com.unboundid.ldap.protocol.LDAPMessage) AddResponseProtocolOp(com.unboundid.ldap.protocol.AddResponseProtocolOp) BindRequestProtocolOp(com.unboundid.ldap.protocol.BindRequestProtocolOp) ModifyDNResponseProtocolOp(com.unboundid.ldap.protocol.ModifyDNResponseProtocolOp) ExtendedRequestProtocolOp(com.unboundid.ldap.protocol.ExtendedRequestProtocolOp) DeleteRequestProtocolOp(com.unboundid.ldap.protocol.DeleteRequestProtocolOp) ModifyRequestProtocolOp(com.unboundid.ldap.protocol.ModifyRequestProtocolOp) Control(com.unboundid.ldap.sdk.Control) BindResponseProtocolOp(com.unboundid.ldap.protocol.BindResponseProtocolOp) ModifyDNRequestProtocolOp(com.unboundid.ldap.protocol.ModifyDNRequestProtocolOp) SearchResultDoneProtocolOp(com.unboundid.ldap.protocol.SearchResultDoneProtocolOp) CompareResponseProtocolOp(com.unboundid.ldap.protocol.CompareResponseProtocolOp) ModifyResponseProtocolOp(com.unboundid.ldap.protocol.ModifyResponseProtocolOp) Test(org.testng.annotations.Test)

Example 55 with LDAPMessage

use of com.unboundid.ldap.protocol.LDAPMessage in project ldapsdk by pingidentity.

the class InMemoryDirectoryServer method compare.

/**
 * {@inheritDoc}
 * <BR><BR>
 * This method may be used regardless of whether the server is listening for
 * client connections, and regardless of whether compare operations are
 * allowed in the server.
 */
@Override()
@NotNull()
public CompareResult compare(@NotNull final CompareRequest compareRequest) throws LDAPException {
    final ArrayList<Control> requestControlList = new ArrayList<>(compareRequest.getControlList());
    requestControlList.add(new Control(InMemoryRequestHandler.OID_INTERNAL_OPERATION_REQUEST_CONTROL, false));
    final LDAPMessage responseMessage = inMemoryHandler.processCompareRequest(1, new CompareRequestProtocolOp(compareRequest.getDN(), compareRequest.getAttributeName(), compareRequest.getRawAssertionValue()), requestControlList);
    final CompareResponseProtocolOp compareResponse = responseMessage.getCompareResponseProtocolOp();
    final LDAPResult compareResult = new LDAPResult(responseMessage.getMessageID(), ResultCode.valueOf(compareResponse.getResultCode()), compareResponse.getDiagnosticMessage(), compareResponse.getMatchedDN(), compareResponse.getReferralURLs(), responseMessage.getControls());
    switch(compareResponse.getResultCode()) {
        case ResultCode.COMPARE_TRUE_INT_VALUE:
        case ResultCode.COMPARE_FALSE_INT_VALUE:
            return new CompareResult(compareResult);
        default:
            throw new LDAPException(compareResult);
    }
}
Also used : Control(com.unboundid.ldap.sdk.Control) LDAPException(com.unboundid.ldap.sdk.LDAPException) CompareRequestProtocolOp(com.unboundid.ldap.protocol.CompareRequestProtocolOp) ArrayList(java.util.ArrayList) LDAPMessage(com.unboundid.ldap.protocol.LDAPMessage) LDAPResult(com.unboundid.ldap.sdk.LDAPResult) CompareResponseProtocolOp(com.unboundid.ldap.protocol.CompareResponseProtocolOp) CompareResult(com.unboundid.ldap.sdk.CompareResult) NotNull(com.unboundid.util.NotNull)

Aggregations

LDAPMessage (com.unboundid.ldap.protocol.LDAPMessage)92 NotNull (com.unboundid.util.NotNull)72 LDAPException (com.unboundid.ldap.sdk.LDAPException)42 Control (com.unboundid.ldap.sdk.Control)25 LogRecord (java.util.logging.LogRecord)24 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)23 ArrayList (java.util.ArrayList)19 TransactionSpecificationRequestControl (com.unboundid.ldap.sdk.controls.TransactionSpecificationRequestControl)14 LDAPResult (com.unboundid.ldap.sdk.LDAPResult)13 AssertionRequestControl (com.unboundid.ldap.sdk.controls.AssertionRequestControl)13 AuthorizationIdentityRequestControl (com.unboundid.ldap.sdk.controls.AuthorizationIdentityRequestControl)13 AuthorizationIdentityResponseControl (com.unboundid.ldap.sdk.controls.AuthorizationIdentityResponseControl)13 DontUseCopyRequestControl (com.unboundid.ldap.sdk.controls.DontUseCopyRequestControl)13 DraftLDUPSubentriesRequestControl (com.unboundid.ldap.sdk.controls.DraftLDUPSubentriesRequestControl)13 ManageDsaITRequestControl (com.unboundid.ldap.sdk.controls.ManageDsaITRequestControl)13 PermissiveModifyRequestControl (com.unboundid.ldap.sdk.controls.PermissiveModifyRequestControl)13 PostReadRequestControl (com.unboundid.ldap.sdk.controls.PostReadRequestControl)13 PostReadResponseControl (com.unboundid.ldap.sdk.controls.PostReadResponseControl)13 PreReadRequestControl (com.unboundid.ldap.sdk.controls.PreReadRequestControl)13 PreReadResponseControl (com.unboundid.ldap.sdk.controls.PreReadResponseControl)13