mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

sin
23.37.2007 594d7dc0035cd90e3faa469fdd1d5e178e0efae8
Bug# 428: Adding support for rejecting unauthenticated requests
1 files added
5 files modified
960 ■■■■■ changed files
opends/resource/bin/start-ds.bat 4 ●●●● patch | view | raw | blame | history
opends/src/server/org/opends/server/core/CoreConfigManager.java 103 ●●●●● patch | view | raw | blame | history
opends/src/server/org/opends/server/core/DirectoryServer.java 70 ●●●●● patch | view | raw | blame | history
opends/src/server/org/opends/server/messages/ConfigMessages.java 34 ●●●●● patch | view | raw | blame | history
opends/src/server/org/opends/server/messages/CoreMessages.java 12 ●●●●● patch | view | raw | blame | history
opends/tests/unit-tests-testng/src/server/org/opends/server/core/RejectUnauthReqTests.java 737 ●●●●● patch | view | raw | blame | history
opends/resource/bin/start-ds.bat
@@ -69,14 +69,14 @@
:runNoDetach
if not exist "%DIR_HOME%\logs\server.out" echo. > "%DIR_HOME%\logs\server.out"
if not exist "%DIR_HOME%\logs\server.starting" echo. > "%DIR_HOME%\logs\server.starting"
"%JAVA_BIN%" %JAVA_ARGS% org.opends.server.core.DirectoryServer --configClass org.opends.server.extensions.ConfigFileHandler --configFile "%DIR_HOME%\config\config.ldif" %*
"%JAVA_BIN%" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 %JAVA_ARGS% org.opends.server.core.DirectoryServer --configClass org.opends.server.extensions.ConfigFileHandler --configFile "%DIR_HOME%\config\config.ldif" %*
goto end
:runDetach
if not exist "%DIR_HOME%\logs\server.out" echo. > "%DIR_HOME%\logs\server.out"
if not exist "%DIR_HOME%\logs\server.starting" echo. > "%DIR_HOME%\logs\server.starting"
start "OpenDS %DIR_HOME%" /B "%JAVA_BIN%" %JAVA_ARGS% org.opends.server.core.DirectoryServer --configClass org.opends.server.extensions.ConfigFileHandler --configFile "%DIR_HOME%\config\config.ldif" %*
start "OpenDS %DIR_HOME%" /B "%JAVA_BIN%" -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 %JAVA_ARGS% org.opends.server.core.DirectoryServer --configClass org.opends.server.extensions.ConfigFileHandler --configFile "%DIR_HOME%\config\config.ldif" %*
"%JAVA_BIN%" -Xms8M -Xmx8M org.opends.server.tools.WaitForFileDelete --targetFile "%DIR_HOME%\logs\server.starting" --logFile "%DIR_HOME%\logs\server.out"
goto end
opends/src/server/org/opends/server/core/CoreConfigManager.java
@@ -769,7 +769,40 @@
      DirectoryServer.setBindWithDNRequiresPassword(
                           DEFAULT_BIND_WITH_DN_REQUIRES_PW);
    }
   // Determine whether an uauthenticated request should be rejected.
    msgID = MSGID_CONFIG_CORE_DESCRIPTION_REJECT_UNAUTHENTICATED_REQUESTS;
    BooleanConfigAttribute rejectRequestStub =
    new BooleanConfigAttribute(ATTR_REJECT_UNAUTHENTICATED_REQ,
                              getMessage(msgID), false);
    try
    {
      BooleanConfigAttribute rejectRequestAttr=
      (BooleanConfigAttribute)
      configRoot.getConfigAttribute(rejectRequestStub);
      if(rejectRequestAttr== null)
      {
        DirectoryServer.setRejectUnauthenticatedRequests(
                       DEFAULT_REJECT_UNAUTHENTICATED_REQ);
      }
      else
      {
        DirectoryServer.setRejectUnauthenticatedRequests(
                       rejectRequestAttr.activeValue());
      }
    }
    catch (Exception e)
    {
      // An error occurred, but this should not be considered fatal.  Log an
      // error message and use the default.
      assert debugException(CLASS_NAME, "initializeCoreConfig", e);
      logError(ErrorLogCategory.CONFIGURATION, ErrorLogSeverity.SEVERE_ERROR,
         MSGID_CONFIG_CORE_REJECT_UNAUTHENTICATED_REQUESTS_INVALID,
         String.valueOf(configEntryDN.toString()), String.valueOf(e));
      DirectoryServer.setRejectUnauthenticatedRequests(
                       DEFAULT_REJECT_UNAUTHENTICATED_REQ);
    }
    DirectoryServer.registerConfigurableComponent(this);
  }
@@ -1641,6 +1674,30 @@
    }
    // See if the entry specifies whether unauthenticated requests should be
    // rejected.
    msgID = MSGID_CONFIG_CORE_DESCRIPTION_REJECT_UNAUTHENTICATED_REQUESTS;
    BooleanConfigAttribute rejectRequestStub =
    new BooleanConfigAttribute(ATTR_REJECT_UNAUTHENTICATED_REQ,
                              getMessage(msgID), false);
    try
    {
      BooleanConfigAttribute rejectRequestAttr=
          (BooleanConfigAttribute)
              configEntry.getConfigAttribute(rejectRequestStub);
    }
    catch (Exception e)
    {
      assert debugException(CLASS_NAME, "hasAcceptableConfiguration", e);
      // An error occurred, so the provided value must not be valid.
      msgID = MSGID_CONFIG_CORE_REJECT_UNAUTHENTICATED_REQUESTS_INVALID;
      unacceptableReasons.add(getMessage(msgID, configEntry.getDN().toString(),
                                         String.valueOf(e)));
      configIsAcceptable = false;
    }
    // Get the DN of the default password policy configuration entry.  It must
    // be provided, and the DN must be associated with a valid password policy.
    msgID = MSGID_CONFIG_CORE_DESCRIPTION_DEFAULT_PWPOLICY_DN;
@@ -2289,6 +2346,41 @@
    }
    // Determine whether an uauthenticated request should be rejected.
    boolean rejectUnauthenticatedReq = DEFAULT_REJECT_UNAUTHENTICATED_REQ;
    msgID = MSGID_CONFIG_CORE_DESCRIPTION_REJECT_UNAUTHENTICATED_REQUESTS;
    BooleanConfigAttribute rejectRequestStub =
    new BooleanConfigAttribute(ATTR_REJECT_UNAUTHENTICATED_REQ,
                              getMessage(msgID), false);
    try
    {
      BooleanConfigAttribute rejectRequestAttr=
      (BooleanConfigAttribute)
      configEntry.getConfigAttribute(rejectRequestStub);
      if(rejectRequestAttr!= null)
      {
        rejectUnauthenticatedReq = rejectRequestAttr.pendingValue();
      }
    }
    catch (Exception e)
    {
       assert debugException(CLASS_NAME, "applyNewConfiguration", e);
      // An error occurred, so we will not allow this configuration change to
      // take place.
      if (resultCode == ResultCode.SUCCESS)
      {
        resultCode = ResultCode.INVALID_ATTRIBUTE_SYNTAX;
      }
      msgID = MSGID_CONFIG_CORE_REJECT_UNAUTHENTICATED_REQUESTS_INVALID;
      resultMessages.add(getMessage(msgID, configEntry.getDN().toString(),
                                    String.valueOf(e)));
    }
    // Ge the DN of the default password policy configuration entry.
    DN defaultPWPolicyDN = null;
    msgID = MSGID_CONFIG_CORE_DESCRIPTION_DEFAULT_PWPOLICY_DN;
@@ -2485,6 +2577,17 @@
                                      String.valueOf(defaultPWPolicyDN),
                                      configEntryDN.toString()));
      }
      DirectoryServer.setRejectUnauthenticatedRequests(
                        rejectUnauthenticatedReq);
      if (detailedResults)
      {
        resultMessages.add(getMessage(MSGID_CONFIG_SET_ATTRIBUTE,
                                      ATTR_REJECT_UNAUTHENTICATED_REQ,
                                      String.valueOf(rejectUnauthenticatedReq),
                                      configEntryDN.toString()));
      }
    }
opends/src/server/org/opends/server/core/DirectoryServer.java
@@ -255,6 +255,9 @@
  // Indicates whether the server is currently in the process of shutting down.
  private boolean shuttingDown;
  // Indicates whether the server should reject unauthenticated requests.
  private boolean rejectUnauthenticatedRequests;
  // The certificate mapper used to establish a mapping between client
  // certificates and user entries.
  private CertificateMapper certificateMapper;
@@ -6647,6 +6650,41 @@
    }
    //Reject or accept the unauthenticated requests based on the configuration
    // settings.
    if(directoryServer.rejectUnauthenticatedRequests &&
        !clientConnection.getAuthenticationInfo().isAuthenticated())
    {
      switch(operation.getOperationType())
      {
        case ADD:
        case COMPARE:
        case DELETE:
        case SEARCH:
        case MODIFY:
        case MODIFY_DN:
         int msgID = MSGID_REJECT_UNAUTHENTICATED_OPERATION;
         String message = getMessage(msgID);
         throw new DirectoryException(
         ResultCode.UNWILLING_TO_PERFORM,message,msgID);
        case EXTENDED:
         ExtendedOperation extOp      = (ExtendedOperation) operation;
         String   requestOID = extOp.getRequestOID();
         if (!((requestOID != null) &&
                 requestOID.equals(OID_START_TLS_REQUEST)))
         {
            msgID = MSGID_REJECT_UNAUTHENTICATED_OPERATION;
            message = getMessage(msgID);
            throw new DirectoryException(
              ResultCode.UNWILLING_TO_PERFORM,message,msgID);
         }
         break;
      }
    }
    // If the associated user is required to change their password before
    // continuing, then make sure the associated operation is one that could
    // result in the password being changed.  If not, then reject it.
@@ -7559,6 +7597,38 @@
  /**
   * Indicates whether an unauthenticated request should be rejected.
   *
   * @return <CODE>true</CODE>if an unauthenticated request should be
   *         rejected, or <CODE>false</CODE>f if not.
   */
  public static boolean rejectUnauthenticatedRequests()
  {
     assert debugEnter(CLASS_NAME, "rejectUnauthenticatedRequests");
     return directoryServer.rejectUnauthenticatedRequests;
  }
  /**
   * Specifies whether an unauthenticated request should be rejected.
   *
   * @param  rejectUnauthenticatedRequests   Indicates whether an
   *                                        unauthenticated request should
   *                                        be rejected.
   */
  public static void setRejectUnauthenticatedRequests(boolean
                          rejectUnauthenticatedRequests)
  {
        assert debugEnter(CLASS_NAME, "rejectUnauthenticatedRequests",
                         String.valueOf(rejectUnauthenticatedRequests));
        directoryServer.rejectUnauthenticatedRequests =
                                  rejectUnauthenticatedRequests;
  }
  /**
   * Retrieves the DN of the configuration entry with which this alert generator
   * is associated.
   *
opends/src/server/org/opends/server/messages/ConfigMessages.java
@@ -6196,6 +6196,26 @@
       CATEGORY_MASK_CONFIG | SEVERITY_MASK_SEVERE_ERROR | 575;
  /**
   * The message ID for the description of whether the server should
   * reject unauthenticated requests.  This does not take any arguments.
   */
  public static final int
      MSGID_CONFIG_CORE_DESCRIPTION_REJECT_UNAUTHENTICATED_REQUESTS =
            CATEGORY_MASK_CONFIG | SEVERITY_MASK_INFORMATIONAL | 576;
  /**
   * The message ID for the message that will be used if an error occurs while
   * trying to process the server configuration for rejecting the
   * unauthenticated operations.This takes two arguments, which are the DN of
   * the configuration entry and a string representation of the exception that
   * was caught.
   */
  public static final int
      MSGID_CONFIG_CORE_REJECT_UNAUTHENTICATED_REQUESTS_INVALID =
           CATEGORY_MASK_CONFIG | SEVERITY_MASK_SEVERE_ERROR | 577;
  /**
   * Associates a set of generic messages with the message IDs defined in this
@@ -8981,6 +9001,20 @@
                   "Unable to set the requested file permissions to the " +
                   "backend database directory. The requested permissions " +
                   "will result in an inaccessable database.");
    registerMessage(
        MSGID_CONFIG_CORE_DESCRIPTION_REJECT_UNAUTHENTICATED_REQUESTS,
                    "Indicates whether the Directory Server should reject  " +
                    "requests from unauthenticated clients. If this is set " +
                    "to \"true\", then unauthenticated clients will only be "+
                    "allowed to send bind and StartTLS requests. Changes to "+
                    "this configuration attribute will take effect " +
                    "immediately.");
    registerMessage(MSGID_CONFIG_CORE_REJECT_UNAUTHENTICATED_REQUESTS_INVALID,
                    "Configuration entry %s has an invalid value for" +
                    "configuration attribute " +
                    ATTR_REJECT_UNAUTHENTICATED_REQ + "(the value should " +
                    "be either true or false)");
  }
}
opends/src/server/org/opends/server/messages/CoreMessages.java
@@ -6067,6 +6067,14 @@
       CATEGORY_MASK_CORE | SEVERITY_MASK_MILD_ERROR | 579;
  /**
   * The message ID for the message that will be used if an attempt is made to
   * do certain operations using an unauthenticated connection.
   */
  public static final int MSGID_REJECT_UNAUTHENTICATED_OPERATION =
       CATEGORY_MASK_CORE | SEVERITY_MASK_MILD_ERROR | 580;
  /**
   * Associates a set of generic messages with the message IDs defined
@@ -8208,6 +8216,10 @@
                    "accessing entries in this portion of the hierarchy " +
                    "because of the missing entries that had been held in " +
                    "the de-registered backend.");
    registerMessage(MSGID_REJECT_UNAUTHENTICATED_OPERATION,
                     "Rejecting the requested operation  " +
                     "because the connection has not been authenticated.");
  }
}
opends/tests/unit-tests-testng/src/server/org/opends/server/core/RejectUnauthReqTests.java
New file
@@ -0,0 +1,737 @@
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Portions Copyright 2006 Sun Microsystems, Inc.
 */
package org.opends.server.core;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.opends.server.TestCaseUtils;
import org.opends.server.protocols.asn1.ASN1OctetString;
import org.opends.server.protocols.internal.InternalClientConnection;
import org.opends.server.types.DN;
import org.opends.server.types.AuthenticationInfo;
import org.opends.server.types.ResultCode;
import org.opends.server.protocols.asn1.ASN1Reader;
import org.opends.server.protocols.asn1.ASN1Writer;
import org.opends.server.protocols.ldap.LDAPControl;
import org.opends.server.protocols.ldap.LDAPMessage;
import org.opends.server.protocols.ldap.UnbindRequestProtocolOp;
import org.opends.server.protocols.ldap.LDAPException;
import org.opends.server.tools.*;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import static org.opends.server.util.ServerConstants.*;
/**
 * A set of testcases for configuration attribute
 * "ds-cfg-reject-unauthenticated-requests".
 *
 */
public class RejectUnauthReqTests extends CoreTestCase
{
  /**
   * Utility method which is called by the testcase sending an ADD request.
   * @param authentication The flag to set the authentication on and off.
   * @return The error code of operation performed.
   * @throws  Exception  If an unexpected problem occurs.
   */
  private int performAddOperation(boolean authentication) throws Exception
  {
    String filePath = TestCaseUtils.createTempFile(
      "dn: o=rejectTestCase,o=test",
      "objectclass: top",
      "objectclass: organization",
      "o: rejectTestCase",
      "description: Reject Test Case");
    String[] args = null;
    if(authentication)
      args = new String []
      {
        "-h", "127.0.0.1",
        "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
        "-D","cn=directory manager",
        "-w","password",
        "-a",
        "-f", filePath,
      };
    else
      args = new String[]
      {
        "-h", "127.0.0.1",
        "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
        "-a",
        "-f", filePath,
      };
    return LDAPModify.mainModify(args, false, null,null);
  }
  /**
   * Utility method which is called by the testcase sending a MODIFY request.
   * @param authentication The flag to set the authentication on and off.
   * @return The error code of operation performed.
   * @throws  Exception  If an unexpected problem occurs.
   */
  private int performModifyOperation(boolean authentication) throws Exception
  {
    String path = TestCaseUtils.createTempFile(
       "dn: o=rejectTestCase,o=test",
       "changetype: modify",
       "replace: description",
       "description: New Description");
    String[] args = null;
    if(authentication)
      args = new String[]
      {
        "-h", "127.0.0.1",
        "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
        "-D","cn=directory manager",
        "-w","password",
        "-f", path
      };
    else
      args = new String[]
      {
        "-h", "127.0.0.1",
        "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
        "-f", path
      };
    return LDAPModify.mainModify(args, false, null, null);
  }
  /**
   * Utility method which is called by the testcase sending a COMPARE request.
   * @param authentication The flag to set the authentication on and off.
   * @return The error code of operation performed.
   * @throws  Exception  If an unexpected problem occurs.
   */
  private int performCompareOperation(boolean authentication) throws Exception
  {
    String[] args = null;
    if(authentication)
      args = new String[]
      {
        "-h", "127.0.0.1",
        "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
        "-D", "cn=Directory Manager",
        "-w", "password",
        "o:test",
        "o=test"
      };
    else
      args = new String[]
      {
        "-h", "127.0.0.1",
        "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
        "o:test",
        "o=test"
      };
    return LDAPCompare.mainCompare(args, false, null, null);
  }
  /**
   * Utility method which is called by the testcase sending a MODRDN request.
   * @param authentication The flag to set the authentication on and off.
   * @return The error code of operation performed.
   * @throws  Exception  If an unexpected problem occurs.
   */
  private int performModRdnOperation(boolean authentication) throws Exception
  {
    String path= TestCaseUtils.createTempFile("dn: o=rejectTestCase,o=Test",
      "changetype: modrdn",
      "newrdn: o=mod_rejectTestCase",
      "deleteoldrdn: 0");
    String[] args = null;
    if(authentication)
      args = new String[]
      {
        "-h", "127.0.0.1",
        "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
        "-D","cn=directory manager",
        "-w","password",
        "-f", path
      };
    else
      args = new String[]
      {
        "-h", "127.0.0.1",
        "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
        "-f", path
      };
    return LDAPModify.mainModify(args, false, null, null);
  }
  /**
   * Utility method which is called by the testcase sending a DELETE request.
   * @param authentication The flag to set the authentication on and off.
   * @return The error code of operation performed.
   * @throws  Exception  If an unexpected problem occurs.
   */
  private int performDeleteOperation(boolean authentication) throws Exception
  {
    String[] args = null;
    if(authentication)
      args = new String[]
      {
        "-h", "127.0.0.1",
        "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
        "-V", "3",
        "-D", "cn=Directory Manager",
        "-w", "password",
        "o=mod_rejectTestCase,o=test"
      };
    else
      args = new String[]
      {
        "-h", "127.0.0.1",
        "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
        "o=mod_rejectTestCase,o=test"
      };
    return LDAPDelete.mainDelete(args, false, null, null);
  }
  /**
   * Ensures that the Directory Server is running before executing the
   * testcases.
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @BeforeClass()
  public void startServer()
         throws Exception
  {
    TestCaseUtils.startServer();
    TestCaseUtils.initializeTestBackend(true);
  }
  /**
   * Tests whether an authenticated SEARCH request will be allowed with the
   * default configuration settings for
   * "ds-cfg-reject-unauthenticated-requests".
   */
  @Test()
  public void testAuthSearchDefCfg()
  {
    String[] args = {
      "-h", "127.0.0.1",
      "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-D", "cn=Directory Manager",
      "-w", "password",
      "-b", "",
      "-s", "base",
      "(objectClass=*)"
      };
    assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
  }
  /**
   * Tests whether an unauthenticated SEARCH request will be allowed with the
   * default configuration settings for
   * "ds-cfg-reject-unauthenticated-requests".
   */
  @Test()
  public void testUnauthSearchDefCfg()
  {
    String[] args = {
      "-h", "127.0.0.1",
      "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-b", "",
      "-s", "base",
      "(objectClass=*)"
      };
    assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
  }
  /**
   * Tests whether an authenticated BIND request will be allowed with the
   * default configuration settings for
   * "ds-cfg-reject-unauthenticated-requests" .
   */
  @Test()
  public void testAuthBindDefCfg()
  {
    InternalClientConnection conn =
       new InternalClientConnection(new AuthenticationInfo());
    ASN1OctetString user =
       new ASN1OctetString("cn=Directory Manager");
    ASN1OctetString password =
       new ASN1OctetString("password");
    BindOperation bindOperation = conn.processSimpleBind(user,password);
    assertEquals(bindOperation.getResultCode(), ResultCode.SUCCESS);
  }
  /**
   * Tests whether an Unauthenticated BIND request will be allowed with the
   * default configuration settings for
   * "ds-cfg-reject-unauthenticated-requests".
   */
  @Test()
  public void testUnauthBindDefCfg()
  {
    InternalClientConnection conn =
        new InternalClientConnection(new AuthenticationInfo());
    BindOperation bindOperation = conn.processSimpleBind(DN.nullDN(),null);
    assertEquals(bindOperation.getResultCode(), ResultCode.SUCCESS);
  }
  /**
   * Tests whether the Who Am I? extended operation with an internal
   * authenticated connection succeeds with default setting of
   * "ds-cfg-reject-unauthenticated-requests".
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @Test()
  public void testAuthWAIDefCfg() throws Exception
  {
    Socket s = new Socket("127.0.0.1", (int) TestCaseUtils.getServerLdapPort());
    ASN1Reader reader = new ASN1Reader(s);
    ASN1Writer writer = new ASN1Writer(s);
    AtomicInteger nextMessageID = new AtomicInteger(1);
    LDAPAuthenticationHandler authHandler =
         new LDAPAuthenticationHandler(reader, writer, "localhost",
                                       nextMessageID);
    authHandler.doSimpleBind(3, new ASN1OctetString("cn=Directory Manager"),
                             new ASN1OctetString("password"),
                             new ArrayList<LDAPControl>(),
                             new ArrayList<LDAPControl>());
    ASN1OctetString authzID = authHandler.requestAuthorizationIdentity();
    assertNotNull(authzID);
    LDAPMessage unbindMessage = new LDAPMessage(nextMessageID.getAndIncrement(),
                                                new UnbindRequestProtocolOp());
    writer.writeElement(unbindMessage.encode());
    s.close();
  }
  /**
   * Tests whether the who am I? extended operation with an internal
   * unauthenticated connection succeeds with default setting of
   * "ds-cfg-reject-unauthenticated-requests".
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @Test()
  public void testUnauthWAIDefCfg() throws Exception
  {
    Socket s = new Socket("127.0.0.1", (int) TestCaseUtils.getServerLdapPort());
    ASN1Reader reader = new ASN1Reader(s);
    ASN1Writer writer = new ASN1Writer(s);
    AtomicInteger nextMessageID = new AtomicInteger(1);
    LDAPAuthenticationHandler authHandler =
         new LDAPAuthenticationHandler(reader, writer, "localhost",
                                       nextMessageID);
    ASN1OctetString authzID = authHandler.requestAuthorizationIdentity();
    assertNull(authzID);
    LDAPMessage unbindMessage = new LDAPMessage(nextMessageID.getAndIncrement(),
                                                new UnbindRequestProtocolOp());
    writer.writeElement(unbindMessage.encode());
    s.close();
  }
  /**
   * Tests the use of the StartTLS extended operation to communicate with the
   * server in conjunction with no authentication and using blind trust
   * with the default configuration settings.
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @Test()
  public void testStartTLSUnauthDefCfg() throws Exception
  {
    String[] argSearch =
    {
     "-h", "127.0.0.1",
     "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
     "-D", "cn=directory manager",
     "-w", "password",
     "-q",
     "-X",
     "-b", "",
     "-s", "base",
     "(objectClass=*)"
    };
    assertEquals(LDAPSearch.mainSearch(
                    argSearch, false, null, System.err),0);
  }
  /**
   * Tests the whether the authenticated ADD,MODIFY,COMPARE,MODRDN and DELETE
   * requests succeed with the default configuration settings.
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @Test()
  public void testOtherOpsAuthDefCfg() throws Exception
  {
    assertEquals(performAddOperation(true),0);
    assertEquals(performModifyOperation(true),0);
    assertEquals(performCompareOperation(true), 0);
    assertEquals(performModRdnOperation(true), 0);
    assertEquals(performDeleteOperation(true),0);
  }
  /**
   * Tests the whether the unauthenticated ADD,MODIFY,COMPARE,MODRDN and
   * DELETE requests succeed with the default configuration settings.
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @Test()
  public void testOtherOpsUnauthDefCfg() throws Exception
  {
    assertEquals(performAddOperation(false),0);
    assertEquals(performModifyOperation(false),0);
    assertEquals(performCompareOperation(false), 0);
    assertEquals(performModRdnOperation(false), 0);
    assertEquals(performDeleteOperation(false),0);
  }
  /**
   * Tests whether change in the configuration attribute takes effect
   * on-the-fly.
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @Test(dependsOnMethods = {
    "org.opends.server.core.RejectUnauthReqTests.testAuthSearchDefCfg",
    "org.opends.server.core.RejectUnauthReqTests.testUnauthSearchDefCfg",
    "org.opends.server.core.RejectUnauthReqTests.testAuthBindDefCfg",
    "org.opends.server.core.RejectUnauthReqTests.testUnauthBindDefCfg",
    "org.opends.server.core.RejectUnauthReqTests.testUnauthWAIDefCfg",
    "org.opends.server.core.RejectUnauthReqTests.testAuthWAIDefCfg",
    "org.opends.server.core.RejectUnauthReqTests.testStartTLSUnauthDefCfg",
    "org.opends.server.core.RejectUnauthReqTests.testOtherOpsUnauthDefCfg",
    "org.opends.server.core.RejectUnauthReqTests.testOtherOpsAuthDefCfg"
  })
  public void  testChangeAndVerifyRejUnauthReqCfgAttr()  throws Exception
  {
    //Verify the default setting of the configuration attribute.
    assertEquals(DirectoryServer.rejectUnauthenticatedRequests(),false);
    String path = TestCaseUtils.createTempFile(
       "dn: cn=config",
       "changetype: modify",
       "replace: ds-cfg-reject-unauthenticated-requests",
       "ds-cfg-reject-unauthenticated-requests: true");
    String[] args =
    {
      "-h", "127.0.0.1",
      "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-D", "cn=Directory Manager",
      "-w", "password",
      "-f",  path
    };
    assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
    assertEquals(DirectoryServer.rejectUnauthenticatedRequests(),true);
  }
  /**
   * Tests whether both authenticated and unauthenticated SEARCH requests
   *  will be allowed with the  new configuration settings for
   * "ds-cfg-reject-unauthenticated-requests" .
   */
  @Test(dependsOnMethods = {
    "org.opends.server.core.RejectUnauthReqTests." +
           "testChangeAndVerifyRejUnauthReqCfgAttr"
  })
  public void testSearchNewCfg()
  {
    String[] args = {
      "-h", "127.0.0.1",
      "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-b", "",
      "-s", "base",
      "(objectClass=*)"
      };
    assertFalse(LDAPSearch.mainSearch(args, false, null, null)==0);
    String[] authArgs =  {
     "-h", "127.0.0.1",
      "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-D", "cn=Directory Manager",
      "-w", "password",
      "-b", "",
      "-s", "base",
      "(objectClass=*)"
    }  ;
    assertEquals(LDAPSearch.mainSearch(
                  authArgs, false, null, System.err), 0);
  }
   /**
   * Tests whether authenticated and unauthenticated BIND requests will be
    * allowed with the new configuration settings for
   * "ds-cfg-reject-unauthenticated-requests" .
   */
  @Test(dependsOnMethods = {
    "org.opends.server.core.RejectUnauthReqTests." +
        "testChangeAndVerifyRejUnauthReqCfgAttr"})
  public void testBindNewCfg()
  {
    InternalClientConnection conn =
          new InternalClientConnection(new AuthenticationInfo());
    ASN1OctetString user =
          new ASN1OctetString("cn=Directory Manager");
    ASN1OctetString password =
          new ASN1OctetString("password");
    //Unauthenticated BIND request.
    BindOperation bindOperation = conn.processSimpleBind(DN.nullDN(),null);
    assertEquals(bindOperation.getResultCode(), ResultCode.SUCCESS);
    //Authenticated BIND request.
    bindOperation = conn.processSimpleBind(user,password);
    assertEquals(bindOperation.getResultCode(), ResultCode.SUCCESS);
  }
  /**
   * Tests the use of the StartTLS extended operation to communicate with the
   * server in conjunction with no authentication and using blind trust.
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @Test(dependsOnMethods = {
    "org.opends.server.core.RejectUnauthReqTests." +
        "testChangeAndVerifyRejUnauthReqCfgAttr"})
  public void testStartTLSNoAuthTrustAll() throws Exception
  {
    String[] argSearch =
    {
     "-h", "127.0.0.1",
     "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
     "-D", "cn=directory manager",
     "-w", "password",
     "-q",
     "-X",
     "-b", "",
     "-s", "base",
     "(objectClass=*)"
    };
    assertEquals(LDAPSearch.mainSearch(
                    argSearch, false, null, System.err),0);
  }
  /**
   * Tests whether the Who Am I? extended operation with an internal
   * authenticated connection succeeds with new setting of
   * "ds-cfg-reject-unauthenticated-requests".
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @Test(dependsOnMethods = {
    "org.opends.server.core.RejectUnauthReqTests." +
        "testChangeAndVerifyRejUnauthReqCfgAttr"})
  public void testAuthWAINewCfg() throws Exception
  {
    InternalClientConnection conn =
       InternalClientConnection.getRootConnection();
    ExtendedOperation extOp =
       conn.processExtendedOperation(OID_WHO_AM_I_REQUEST, null);
    assertEquals(extOp.getResultCode(), ResultCode.SUCCESS);
    assertNotNull(extOp.getResponseValue());
  }
  /**
   * Tests whether the who am I? extended operation with an
   * unauthenticated connection fails with new setting of
   * "ds-cfg-reject-unauthenticated-requests".
   *
   * @throws  UnsupportedEncodingException If an unexpected problem occurs.
   * @throws  IOException If an unexpected problem occurs.
   * @throws  ClientException If an unexpected problem occurs.
   */
  @Test(dependsOnMethods = {
    "org.opends.server.core.RejectUnauthReqTests." +
        "testChangeAndVerifyRejUnauthReqCfgAttr"})
  public void testUnauthWAINewCfg() throws UnsupportedEncodingException,
                                          IOException,ClientException
  {
    Socket s = new Socket("127.0.0.1", (int) TestCaseUtils.getServerLdapPort());
    ASN1Reader reader = new ASN1Reader(s);
    ASN1Writer writer = new ASN1Writer(s);
    AtomicInteger nextMessageID = new AtomicInteger(1);
    LDAPAuthenticationHandler authHandler =
         new LDAPAuthenticationHandler(reader, writer, "localhost",
                                       nextMessageID);
    ASN1OctetString authzID = null;
    try
    {
      authzID = authHandler.requestAuthorizationIdentity();
    }
    catch(LDAPException e)
    {
      assertNull(authzID);
    }
    finally
    {
      LDAPMessage unbindMessage = new LDAPMessage(
                                    nextMessageID.getAndIncrement(),
                                    new UnbindRequestProtocolOp());
      writer.writeElement(unbindMessage.encode());
      s.close();
    }
  }
  /**
   * Tests the whether the authenticated ADD,MODIFY,COMPARE,MODRDN and DELETE
   * requests succeed with the new configuration settings.
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @Test(dependsOnMethods = {
        "org.opends.server.core.RejectUnauthReqTests." +
            "testChangeAndVerifyRejUnauthReqCfgAttr"})
  public void testOtherOpsAuthNewCfg() throws Exception {
    assertEquals(performAddOperation(true),0);
    assertEquals(performModifyOperation(true),0);
    assertEquals(performCompareOperation(true), 0);
    assertEquals(performModRdnOperation(true), 0);
    assertEquals(performDeleteOperation(true),0);
  }
  /**
   * Tests the whether the unauthenticated ADD,MODIFY,COMPARE,MODRDN and
   * DELETE requests fail with the new configuration settings.
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @Test(dependsOnMethods = {
        "org.opends.server.core.RejectUnauthReqTests." +
            "testChangeAndVerifyRejUnauthReqCfgAttr"})
  public void testOtherOpsUnauthNewCfg() throws Exception
  {
    assertFalse(performAddOperation(false)==0);
    assertFalse(performModifyOperation(false)==0);
    assertFalse(performCompareOperation(false)==0);
    assertFalse(performModRdnOperation(false)==0);
    assertFalse(performDeleteOperation(false)==0);
  }
  /**
   * Resets the configuration attribute to the default settings.
   *
   * @throws  Exception  If an unexpected problem occurs.
   */
  @AfterClass()
  public void  testResetRejUnauthReqCfgAttr()  throws Exception
  {
    //Verify the modified setting of the configuration attribute.
    assertEquals(DirectoryServer.rejectUnauthenticatedRequests(),true);
    String path = TestCaseUtils.createTempFile(
       "dn: cn=config",
       "changetype: modify",
       "replace: ds-cfg-reject-unauthenticated-requests",
       "ds-cfg-reject-unauthenticated-requests: false");
    String[] args =
    {
      "-h", "127.0.0.1",
      "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
      "-D", "cn=Directory Manager",
      "-w", "password",
      "-f",  path
    };
    assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
    assertEquals(DirectoryServer.rejectUnauthenticatedRequests(),false);
  }
}