private void checkAuthentication(
      String rootDn, ActiveDirectoryLdapAuthenticationProvider provider) throws NamingException {
    DirContext ctx = mock(DirContext.class);
    when(ctx.getNameInNamespace()).thenReturn("");

    DirContextAdapter dca = new DirContextAdapter();
    SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
    @SuppressWarnings("deprecation")
    DistinguishedName searchBaseDn = new DistinguishedName(rootDn);
    when(ctx.search(
            eq(searchBaseDn), any(String.class), any(Object[].class), any(SearchControls.class)))
        .thenReturn(new MockNamingEnumeration(sr))
        .thenReturn(new MockNamingEnumeration(sr));

    provider.contextFactory = createContextFactoryReturning(ctx);

    Authentication result = provider.authenticate(joe);

    assertEquals(0, result.getAuthorities().size());

    dca.addAttributeValue("memberOf", "CN=Admin,CN=Users,DC=mydomain,DC=eu");

    result = provider.authenticate(joe);

    assertEquals(1, result.getAuthorities().size());
  }
  // SEC-2017
  @Test(expected = BadCredentialsException.class)
  public void noUserSearchCausesUsernameNotFound() throws Exception {
    DirContext ctx = mock(DirContext.class);
    when(ctx.getNameInNamespace()).thenReturn("");
    when(ctx.search(
            any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
        .thenReturn(new EmptyEnumeration<SearchResult>());

    provider.contextFactory = createContextFactoryReturning(ctx);

    provider.authenticate(joe);
  }
  @SuppressWarnings("unchecked")
  @Test(expected = IncorrectResultSizeDataAccessException.class)
  public void duplicateUserSearchCausesError() throws Exception {
    DirContext ctx = mock(DirContext.class);
    when(ctx.getNameInNamespace()).thenReturn("");
    NamingEnumeration<SearchResult> searchResults = mock(NamingEnumeration.class);
    when(searchResults.hasMore()).thenReturn(true, true, false);
    SearchResult searchResult = mock(SearchResult.class);
    when(searchResult.getObject())
        .thenReturn(new DirContextAdapter("ou=1"), new DirContextAdapter("ou=2"));
    when(searchResults.next()).thenReturn(searchResult);
    when(ctx.search(
            any(Name.class), any(String.class), any(Object[].class), any(SearchControls.class)))
        .thenReturn(searchResults);

    provider.contextFactory = createContextFactoryReturning(ctx);

    provider.authenticate(joe);
  }
  @Test
  public void nullDomainIsSupportedIfAuthenticatingWithFullUserPrincipal() throws Exception {
    provider = new ActiveDirectoryLdapAuthenticationProvider(null, "ldap://192.168.1.200/");
    DirContext ctx = mock(DirContext.class);
    when(ctx.getNameInNamespace()).thenReturn("");

    DirContextAdapter dca = new DirContextAdapter();
    SearchResult sr = new SearchResult("CN=Joe Jannsen,CN=Users", dca, dca.getAttributes());
    when(ctx.search(
            eq(new DistinguishedName("DC=mydomain,DC=eu")),
            any(String.class),
            any(Object[].class),
            any(SearchControls.class)))
        .thenReturn(new MockNamingEnumeration(sr));
    provider.contextFactory = createContextFactoryReturning(ctx);

    try {
      provider.authenticate(joe);
      fail("Expected BadCredentialsException for user with no domain information");
    } catch (BadCredentialsException expected) {
    }

    provider.authenticate(new UsernamePasswordAuthenticationToken("*****@*****.**", "password"));
  }
Exemple #5
0
  /**
   * Program Main.
   *
   * <p>Lookup all JMX agents in the LDAP Directory and list their MBeans and attributes.
   *
   * <p>You may wish to use the following properties on the Java command line:
   *
   * <ul>
   *   <li><code>-Dagent.name=&lt;AgentName&gt;</code>: specifies an AgentName to lookup (default is
   *       null, meaning any agent).
   *   <li><code>-Dprotocol=&lt;ProtocolType&gt;</code>: restrains the client to lookup for a
   *       specific protocol type (default is null, meaning any type).
   *   <li><code>-Djava.naming.factory.initial=&lt;initial-context-factory&gt;
   *     </code>: The initial context factory to use for accessing the LDAP directory (see {@link
   *       Context#INITIAL_CONTEXT_FACTORY Context.INITIAL_CONTEXT_FACTORY}) - default is <code>
   *       "com.sun.jndi.ldap.LdapCtxFactory"</code>.
   *   <li><code>-Djava.naming.provider.url=&lt;provider-url&gt;</code>: The LDAP Provider URL (see
   *       {@link Context#PROVIDER_URL Context.PROVIDER_URL}).
   *   <li><code>-Djava.naming.security.principal=&lt;ldap-principal&gt;
   *     </code>: The security principal (login) to use to connect with the LDAP directory (see
   *       {@link Context#SECURITY_PRINCIPAL Context.SECURITY_PRINCIPAL} - default is <code>
   *       "cn=Directory Manager"</code>.
   *   <li><code>-Djava.naming.security.credentials=&lt;ldap-credentials&gt;
   *     </code>: The security credentials (password) to use to connect with the LDAP directory (see
   *       {@link Context#SECURITY_CREDENTIALS Context.SECURITY_CREDENTIALS}).
   *   <li><code>-Ddebug="true|false"</code>: switch the Server debug flag on/off (default is
   *       "false")
   * </ul>
   */
  public static void main(String[] args) {
    try {
      // Get the value of the debug flag.
      //
      debug = (Boolean.valueOf(System.getProperty("debug", "false"))).booleanValue();

      // Get a pointer to the LDAP Directory.
      //
      final DirContext root = getRootContext();
      debug("root is: " + root.getNameInNamespace());

      final String protocolType = System.getProperty("protocol");
      final String agentName = System.getProperty("agent.name");

      // Lookup all matching agents in the LDAP Directory.
      //
      List l = lookup(root, protocolType, agentName);

      // Attempt to connect to retrieved agents
      //
      System.out.println("Number of agents found : " + l.size());
      int j = 1;
      for (Iterator i = l.iterator(); i.hasNext(); j++) {
        JMXConnector c1 = (JMXConnector) i.next();
        if (c1 != null) {

          // Connect
          //
          System.out.println("----------------------------------------------------");
          System.out.println("\tConnecting to agent number " + j);
          System.out.println("----------------------------------------------------");
          debug("JMXConnector is: " + c1);

          // Prepare the environment Map
          //
          final HashMap env = new HashMap();
          final String factory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
          final String ldapServerUrl = System.getProperty(Context.PROVIDER_URL);
          final String ldapUser = System.getProperty(Context.SECURITY_PRINCIPAL);
          final String ldapPasswd = System.getProperty(Context.SECURITY_CREDENTIALS);

          // Transfer some system properties to the Map
          //
          if (factory != null) // this should not be needed
          env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
          if (ldapServerUrl != null) // this should not be needed
          env.put(Context.PROVIDER_URL, ldapServerUrl);
          if (ldapUser != null) // this is needed when LDAP is used
          env.put(Context.SECURITY_PRINCIPAL, ldapUser);
          if (ldapPasswd != null) // this is needed when LDAP is used
          env.put(Context.SECURITY_CREDENTIALS, ldapPasswd);

          try {
            c1.connect(env);
          } catch (IOException x) {
            System.err.println("Connection failed: " + x);
            x.printStackTrace(System.err);
            continue;
          }

          // Get MBeanServerConnection
          //
          MBeanServerConnection conn = c1.getMBeanServerConnection();
          debug("Connection is:" + conn);
          System.out.println("Server domain is: " + conn.getDefaultDomain());

          // List all MBeans
          //
          try {
            listMBeans(conn);
          } catch (IOException x) {
            System.err.println("Failed to list MBeans: " + x);
            x.printStackTrace(System.err);
          }

          // Close connector
          //
          try {
            c1.close();
          } catch (IOException x) {
            System.err.println("Failed to close connection: " + x);
            x.printStackTrace(System.err);
          }
        }
      }
    } catch (Exception x) {
      System.err.println("Unexpected exception caught in main: " + x);
      x.printStackTrace(System.err);
    }
  }
  protected boolean authenticate(String username, String password) throws LoginException {

    MessageFormat userSearchMatchingFormat;
    boolean userSearchSubtreeBool;

    DirContext context = null;

    if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) {
      ActiveMQServerLogger.LOGGER.debug("Create the LDAP initial context.");
    }
    try {
      context = open();
    } catch (NamingException ne) {
      FailedLoginException ex = new FailedLoginException("Error opening LDAP connection");
      ex.initCause(ne);
      throw ex;
    }

    if (!isLoginPropertySet(USER_SEARCH_MATCHING)) return false;

    userSearchMatchingFormat = new MessageFormat(getLDAPPropertyValue(USER_SEARCH_MATCHING));
    userSearchSubtreeBool =
        Boolean.valueOf(getLDAPPropertyValue(USER_SEARCH_SUBTREE)).booleanValue();

    try {

      String filter = userSearchMatchingFormat.format(new String[] {doRFC2254Encoding(username)});
      SearchControls constraints = new SearchControls();
      if (userSearchSubtreeBool) {
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
      } else {
        constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
      }

      // setup attributes
      List<String> list = new ArrayList<String>();
      if (isLoginPropertySet(USER_ROLE_NAME)) {
        list.add(getLDAPPropertyValue(USER_ROLE_NAME));
      }
      String[] attribs = new String[list.size()];
      list.toArray(attribs);
      constraints.setReturningAttributes(attribs);

      if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) {
        ActiveMQServerLogger.LOGGER.debug("Get the user DN.");
        ActiveMQServerLogger.LOGGER.debug("Looking for the user in LDAP with ");
        ActiveMQServerLogger.LOGGER.debug("  base DN: " + getLDAPPropertyValue(USER_BASE));
        ActiveMQServerLogger.LOGGER.debug("  filter: " + filter);
      }

      NamingEnumeration<SearchResult> results =
          context.search(getLDAPPropertyValue(USER_BASE), filter, constraints);

      if (results == null || !results.hasMore()) {
        ActiveMQServerLogger.LOGGER.warn("User " + username + " not found in LDAP.");
        throw new FailedLoginException("User " + username + " not found in LDAP.");
      }

      SearchResult result = results.next();

      if (results.hasMore()) {
        // ignore for now
      }

      String dn;
      if (result.isRelative()) {
        ActiveMQServerLogger.LOGGER.debug("LDAP returned a relative name: " + result.getName());

        NameParser parser = context.getNameParser("");
        Name contextName = parser.parse(context.getNameInNamespace());
        Name baseName = parser.parse(getLDAPPropertyValue(USER_BASE));
        Name entryName = parser.parse(result.getName());
        Name name = contextName.addAll(baseName);
        name = name.addAll(entryName);
        dn = name.toString();
      } else {
        ActiveMQServerLogger.LOGGER.debug("LDAP returned an absolute name: " + result.getName());

        try {
          URI uri = new URI(result.getName());
          String path = uri.getPath();

          if (path.startsWith("/")) {
            dn = path.substring(1);
          } else {
            dn = path;
          }
        } catch (URISyntaxException e) {
          if (context != null) {
            close(context);
          }
          FailedLoginException ex = new FailedLoginException("Error parsing absolute name as URI.");
          ex.initCause(e);
          throw ex;
        }
      }

      if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) {
        ActiveMQServerLogger.LOGGER.debug("Using DN [" + dn + "] for binding.");
      }

      Attributes attrs = result.getAttributes();
      if (attrs == null) {
        throw new FailedLoginException("User found, but LDAP entry malformed: " + username);
      }
      List<String> roles = null;
      if (isLoginPropertySet(USER_ROLE_NAME)) {
        roles = addAttributeValues(getLDAPPropertyValue(USER_ROLE_NAME), attrs, roles);
      }

      // check the credentials by binding to server
      if (bindUser(context, dn, password)) {
        // if authenticated add more roles
        roles = getRoles(context, dn, username, roles);
        if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) {
          ActiveMQServerLogger.LOGGER.debug("Roles " + roles + " for user " + username);
        }
        for (int i = 0; i < roles.size(); i++) {
          groups.add(new RolePrincipal(roles.get(i)));
        }
      } else {
        throw new FailedLoginException("Password does not match for user: "******"Error contacting LDAP");
      ex.initCause(e);
      throw ex;
    } catch (NamingException e) {
      if (context != null) {
        close(context);
      }
      FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
      ex.initCause(e);
      throw ex;
    }

    return true;
  }