Search in sources :

Example 86 with DirContext

use of javax.naming.directory.DirContext in project geode by apache.

the class SocketCreator method reverseDNS.

/**
   * This method uses JNDI to look up an address in DNS and return its name
   * 
   * @param addr
   *
   * @return the host name associated with the address or null if lookup isn't possible or there is
   *         no host name for this address
   */
public static String reverseDNS(InetAddress addr) {
    byte[] addrBytes = addr.getAddress();
    // reverse the address suitable for reverse lookup
    String lookup = "";
    for (int index = addrBytes.length - 1; index >= 0; index--) {
        lookup = lookup + (addrBytes[index] & 0xff) + '.';
    }
    lookup += "in-addr.arpa";
    try {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        DirContext ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(lookup, new String[] { "PTR" });
        for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements(); ) {
            Attribute attr = (Attribute) ae.next();
            for (Enumeration vals = attr.getAll(); vals.hasMoreElements(); ) {
                Object elem = vals.nextElement();
                if ("PTR".equals(attr.getID()) && elem != null) {
                    return elem.toString();
                }
            }
        }
        ctx.close();
    } catch (Exception e) {
    // ignored
    }
    return null;
}
Also used : Enumeration(java.util.Enumeration) NamingEnumeration(javax.naming.NamingEnumeration) Attribute(javax.naming.directory.Attribute) Hashtable(java.util.Hashtable) Attributes(javax.naming.directory.Attributes) NamingEnumeration(javax.naming.NamingEnumeration) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BindException(java.net.BindException) SocketException(java.net.SocketException) SystemConnectException(org.apache.geode.SystemConnectException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) GemFireConfigException(org.apache.geode.GemFireConfigException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnknownHostException(java.net.UnknownHostException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException)

Example 87 with DirContext

use of javax.naming.directory.DirContext in project gerrit by GerritCodeReview.

the class LdapAuthBackend method authenticate.

@Override
public AuthUser authenticate(AuthRequest req) throws MissingCredentialsException, InvalidCredentialsException, UnknownUserException, UserNotAllowedException, AuthException {
    if (req.getUsername() == null) {
        throw new MissingCredentialsException();
    }
    final String username = lowerCaseUsername ? req.getUsername().toLowerCase(Locale.US) : req.getUsername();
    try {
        final DirContext ctx;
        if (authConfig.getAuthType() == AuthType.LDAP_BIND) {
            ctx = helper.authenticate(username, req.getPassword());
        } else {
            ctx = helper.open();
        }
        try {
            final Helper.LdapSchema schema = helper.getSchema(ctx);
            final LdapQuery.Result m = helper.findAccount(schema, ctx, username, false);
            if (authConfig.getAuthType() == AuthType.LDAP) {
                // We found the user account, but we need to verify
                // the password matches it before we can continue.
                //
                helper.authenticate(m.getDN(), req.getPassword()).close();
            }
            return new AuthUser(AuthUser.UUID.create(username), username);
        } finally {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Cannot close LDAP query handle", e);
            }
        }
    } catch (AccountException e) {
        log.error("Cannot query LDAP to authenticate user", e);
        throw new InvalidCredentialsException("Cannot query LDAP for account", e);
    } catch (NamingException e) {
        log.error("Cannot query LDAP to authenticate user", e);
        throw new AuthException("Cannot query LDAP for account", e);
    } catch (LoginException e) {
        log.error("Cannot authenticate server via JAAS", e);
        throw new AuthException("Cannot query LDAP for account", e);
    }
}
Also used : AuthException(com.google.gerrit.server.auth.AuthException) AuthUser(com.google.gerrit.server.auth.AuthUser) DirContext(javax.naming.directory.DirContext) AccountException(com.google.gerrit.server.account.AccountException) InvalidCredentialsException(com.google.gerrit.server.auth.InvalidCredentialsException) LoginException(javax.security.auth.login.LoginException) MissingCredentialsException(com.google.gerrit.server.auth.MissingCredentialsException) NamingException(javax.naming.NamingException)

Example 88 with DirContext

use of javax.naming.directory.DirContext in project gerrit by GerritCodeReview.

the class LdapRealm method authenticate.

@Override
public AuthRequest authenticate(final AuthRequest who) throws AccountException {
    if (config.getBoolean("ldap", "localUsernameToLowerCase", false)) {
        who.setLocalUser(who.getLocalUser().toLowerCase(Locale.US));
    }
    final String username = who.getLocalUser();
    try {
        final DirContext ctx;
        if (authConfig.getAuthType() == AuthType.LDAP_BIND) {
            ctx = helper.authenticate(username, who.getPassword());
        } else {
            ctx = helper.open();
        }
        try {
            final Helper.LdapSchema schema = helper.getSchema(ctx);
            final LdapQuery.Result m = helper.findAccount(schema, ctx, username, fetchMemberOfEagerly);
            if (authConfig.getAuthType() == AuthType.LDAP && !who.isSkipAuthentication()) {
                // We found the user account, but we need to verify
                // the password matches it before we can continue.
                //
                helper.authenticate(m.getDN(), who.getPassword()).close();
            }
            who.setDisplayName(apply(schema.accountFullName, m));
            who.setUserName(apply(schema.accountSshUserName, m));
            if (schema.accountEmailAddress != null) {
                who.setEmailAddress(apply(schema.accountEmailAddress, m));
            } else if (emailExpander.canExpand(username)) {
                // If LDAP cannot give us a valid email address for this user
                // try expanding it through the older email expander code which
                // assumes a user name within a domain.
                //
                who.setEmailAddress(emailExpander.expand(username));
            }
            //
            if (fetchMemberOfEagerly || mandatoryGroup != null) {
                Set<AccountGroup.UUID> groups = helper.queryForGroups(ctx, username, m);
                if (mandatoryGroup != null) {
                    GroupReference mandatoryGroupRef = GroupBackends.findExactSuggestion(groupBackend, mandatoryGroup);
                    if (mandatoryGroupRef == null) {
                        throw new AccountException("Could not identify mandatory group: " + mandatoryGroup);
                    }
                    if (!groups.contains(mandatoryGroupRef.getUUID())) {
                        throw new AccountException("Not member of mandatory LDAP group: " + mandatoryGroupRef.getName());
                    }
                }
                // Regardless if we enabled fetchMemberOfEagerly, we already have the
                // groups and it would be a waste not to cache them.
                membershipCache.put(username, groups);
            }
            return who;
        } finally {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Cannot close LDAP query handle", e);
            }
        }
    } catch (NamingException e) {
        log.error("Cannot query LDAP to authenticate user", e);
        throw new AuthenticationUnavailableException("Cannot query LDAP for account", e);
    } catch (LoginException e) {
        log.error("Cannot authenticate server via JAAS", e);
        throw new AuthenticationUnavailableException("Cannot query LDAP for account", e);
    }
}
Also used : AuthenticationUnavailableException(com.google.gerrit.server.auth.AuthenticationUnavailableException) ParameterizedString(com.google.gerrit.common.data.ParameterizedString) DirContext(javax.naming.directory.DirContext) AccountException(com.google.gerrit.server.account.AccountException) LoginException(javax.security.auth.login.LoginException) NamingException(javax.naming.NamingException) GroupReference(com.google.gerrit.common.data.GroupReference)

Example 89 with DirContext

use of javax.naming.directory.DirContext in project karaf by apache.

the class LDAPLoginModule method doLogin.

protected boolean doLogin() throws LoginException {
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    try {
        callbackHandler.handle(callbacks);
    } catch (IOException ioException) {
        throw new LoginException(ioException.getMessage());
    } catch (UnsupportedCallbackException unsupportedCallbackException) {
        throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
    }
    user = doRFC2254Encoding(((NameCallback) callbacks[0]).getName());
    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
    // If either a username or password is specified don't allow authentication = "none".
    // This is to prevent someone from logging into Karaf as any user without providing a 
    // valid password (because if authentication = none, the password could be any 
    // value - it is ignored).
    LDAPOptions options = new LDAPOptions(this.options);
    if (options.isUsernameTrim()) {
        if (user != null) {
            user = user.trim();
        }
    }
    String authentication = options.getAuthentication();
    if ("none".equals(authentication) && (user != null || tmpPassword != null)) {
        logger.debug("Changing from authentication = none to simple since user or password was specified.");
        // default to simple so that the provided user/password will get checked
        authentication = "simple";
        Map<String, Object> opts = new HashMap<>(this.options);
        opts.put(LDAPOptions.AUTHENTICATION, authentication);
        options = new LDAPOptions(opts);
    }
    boolean allowEmptyPasswords = options.getAllowEmptyPasswords();
    if (!"none".equals(authentication) && !allowEmptyPasswords && (tmpPassword == null || tmpPassword.length == 0)) {
        throw new LoginException("Empty passwords not allowed");
    }
    if (tmpPassword == null) {
        tmpPassword = new char[0];
    }
    String password = new String(tmpPassword);
    principals = new HashSet<>();
    LDAPCache cache = LDAPCache.getCache(options);
    // step 1: get the user DN
    final String[] userDnAndNamespace;
    try {
        logger.debug("Get the user DN.");
        userDnAndNamespace = cache.getUserDnAndNamespace(user);
        if (userDnAndNamespace == null) {
            return false;
        }
    } catch (Exception e) {
        logger.warn("Can't connect to the LDAP server: {}", e.getMessage(), e);
        throw new LoginException("Can't connect to the LDAP server: " + e.getMessage());
    }
    // step 2: bind the user using the DN
    DirContext context = null;
    try {
        // switch the credentials to the Karaf login user so that we can verify his password is correct
        logger.debug("Bind user (authentication).");
        Hashtable<String, Object> env = options.getEnv();
        env.put(Context.SECURITY_AUTHENTICATION, authentication);
        logger.debug("Set the security principal for " + userDnAndNamespace[0] + "," + options.getUserBaseDn());
        env.put(Context.SECURITY_PRINCIPAL, userDnAndNamespace[0] + "," + options.getUserBaseDn());
        env.put(Context.SECURITY_CREDENTIALS, password);
        logger.debug("Binding the user.");
        context = new InitialDirContext(env);
        logger.debug("User " + user + " successfully bound.");
        context.close();
    } catch (Exception e) {
        logger.warn("User " + user + " authentication failed.", e);
        throw new LoginException("Authentication failed: " + e.getMessage());
    } finally {
        if (context != null) {
            try {
                context.close();
            } catch (Exception e) {
            // ignore
            }
        }
    }
    principals.add(new UserPrincipal(user));
    // step 3: retrieving user roles
    try {
        String[] roles = cache.getUserRoles(user, userDnAndNamespace[0], userDnAndNamespace[1]);
        for (String role : roles) {
            principals.add(new RolePrincipal(role));
        }
    } catch (Exception e) {
        throw new LoginException("Can't get user " + user + " roles: " + e.getMessage());
    }
    return true;
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) InitialDirContext(javax.naming.directory.InitialDirContext) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) IOException(java.io.IOException) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) LoginException(javax.security.auth.login.LoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal)

Example 90 with DirContext

use of javax.naming.directory.DirContext in project jmeter by apache.

the class LDAPExtSampler method bindOp.

/***************************************************************************
     * This will do the bind for the User defined Thread, this bind is used for
     * the whole context
     *
     **************************************************************************/
private void bindOp(SampleResult res) throws NamingException {
    DirContext ctx = ldapContexts.remove(getThreadName());
    if (ctx != null) {
        log.warn("Closing previous context for thread: " + getThreadName());
        ctx.close();
    }
    try {
        res.sampleStart();
        ctx = LdapExtClient.connect(getServername(), getPort(), getRootdn(), getUserDN(), getUserPw(), getConnTimeOut(), isSecure());
    } finally {
        res.sampleEnd();
    }
    ldapContexts.put(getThreadName(), ctx);
}
Also used : DirContext(javax.naming.directory.DirContext)

Aggregations

DirContext (javax.naming.directory.DirContext)111 NamingException (javax.naming.NamingException)51 InitialDirContext (javax.naming.directory.InitialDirContext)43 SearchResult (javax.naming.directory.SearchResult)27 SearchControls (javax.naming.directory.SearchControls)24 Attributes (javax.naming.directory.Attributes)21 Attribute (javax.naming.directory.Attribute)17 IOException (java.io.IOException)16 NamingEnumeration (javax.naming.NamingEnumeration)16 Hashtable (java.util.Hashtable)14 Test (org.junit.Test)14 DistinguishedName (org.springframework.ldap.core.DistinguishedName)11 ProxyDirContext (org.apache.naming.resources.ProxyDirContext)10 WebDirContext (org.apache.naming.resources.WebDirContext)9 ArrayList (java.util.ArrayList)8 BaseDirContext (org.apache.naming.resources.BaseDirContext)8 FileDirContext (org.apache.naming.resources.FileDirContext)8 WARDirContext (org.apache.naming.resources.WARDirContext)8 Name (javax.naming.Name)7 BasicAttribute (javax.naming.directory.BasicAttribute)7