Search in sources :

Example 31 with InitialDirContext

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

the class Helper method authenticate.

DirContext authenticate(String dn, String password) throws AccountException {
    final Properties env = createContextProperties();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, dn);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.REFERRAL, referral);
    try {
        return new InitialDirContext(env);
    } catch (NamingException e) {
        throw new AuthenticationFailedException("Incorrect username or password", e);
    }
}
Also used : AuthenticationFailedException(com.google.gerrit.server.account.AuthenticationFailedException) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext) Properties(java.util.Properties)

Example 32 with InitialDirContext

use of javax.naming.directory.InitialDirContext in project nhin-d by DirectProject.

the class LdapPublicCertUtilImpl method ldapSearch.

/**
	 * Searches for certificates in public LDAP servers using the subject name.
	 * @param subjectName The subject's email address or domain name.
	 * @return Collection of certificates matching the LDAP query for the subject name.
	 */
public Collection<X509Certificate> ldapSearch(String subjectName) {
    final Collection<X509Certificate> retVal = new ArrayList<X509Certificate>();
    String domainName;
    // find by host
    int index;
    if ((index = subjectName.indexOf("@")) > -1)
        domainName = subjectName.substring(index + 1);
    else
        domainName = subjectName;
    final String lookupName = LDAP_SRV_PREFIX + domainName;
    InitialDirContext ctx = null;
    try {
        ctx = getDirContext(lookupName);
        if (ctx != null) {
            // discover the naming contexts
            List<String> dNs = getBaseNamingContexts(ctx);
            if (!dNs.isEmpty()) {
                for (String dn : dNs) {
                    NamingEnumeration<SearchResult> searchResult = ctx.search(dn, EMAIL_ATTRIBUTE + "=" + subjectName, getDefaultSearchControls());
                    while (searchResult != null && searchResult.hasMore()) {
                        final SearchResult certEntry = searchResult.nextElement();
                        if (certEntry != null) {
                            final Attributes certAttributes = certEntry.getAttributes();
                            if (certAttributes != null) {
                                // get only the returning cert attribute (for now, ignore all other attributes)
                                Attribute certAttribute = certAttributes.get(CERT_ATTRIBUTE_BINARY);
                                // binary modifier
                                if (certAttribute == null)
                                    certAttribute = certAttributes.get(CERT_ATTRIBUTE);
                                if (certAttribute != null) {
                                    NamingEnumeration<? extends Object> allValues = certAttribute.getAll();
                                    // LDAP may contain a collection of certificates.
                                    while (allValues.hasMoreElements()) {
                                        byte[] rawCert = null;
                                        Object obj = allValues.nextElement();
                                        rawCert = (byte[]) obj;
                                        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
                                        final ByteArrayInputStream inputStream = new ByteArrayInputStream(rawCert);
                                        try {
                                            X509Certificate addCert = (X509Certificate) cf.generateCertificate(inputStream);
                                            retVal.add(addCert);
                                        } finally {
                                            IOUtils.closeQuietly(inputStream);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new NHINDException("", e);
    } finally {
        this.closeDirContext(ctx);
    }
    return retVal;
}
Also used : Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) InitialDirContext(javax.naming.directory.InitialDirContext) CertificateFactory(java.security.cert.CertificateFactory) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) NamingException(javax.naming.NamingException) UnknownHostException(java.net.UnknownHostException) NHINDException(org.nhindirect.stagent.NHINDException) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 33 with InitialDirContext

use of javax.naming.directory.InitialDirContext 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 34 with InitialDirContext

use of javax.naming.directory.InitialDirContext 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 35 with InitialDirContext

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

the class LDAPCache method open.

public synchronized DirContext open() throws NamingException {
    if (isContextAlive()) {
        return context;
    }
    clearCache();
    context = new InitialDirContext(options.getEnv());
    EventDirContext eventContext = ((EventDirContext) context.lookup(""));
    final SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    if (!options.getDisableCache()) {
        String filter = options.getUserFilter();
        filter = filter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement("*"));
        filter = filter.replace("\\", "\\\\");
        eventContext.addNamingListener(options.getUserBaseDn(), filter, constraints, this);
        filter = options.getRoleFilter();
        if (filter != null) {
            filter = filter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement("*"));
            filter = filter.replaceAll(Pattern.quote("%dn"), Matcher.quoteReplacement("*"));
            filter = filter.replaceAll(Pattern.quote("%fqdn"), Matcher.quoteReplacement("*"));
            filter = filter.replace("\\", "\\\\");
            eventContext.addNamingListener(options.getRoleBaseDn(), filter, constraints, this);
        }
    }
    return context;
}
Also used : EventDirContext(javax.naming.event.EventDirContext) SearchControls(javax.naming.directory.SearchControls) InitialDirContext(javax.naming.directory.InitialDirContext)

Aggregations

InitialDirContext (javax.naming.directory.InitialDirContext)37 NamingException (javax.naming.NamingException)18 DirContext (javax.naming.directory.DirContext)18 Hashtable (java.util.Hashtable)17 Attributes (javax.naming.directory.Attributes)9 IOException (java.io.IOException)8 Attribute (javax.naming.directory.Attribute)7 Properties (java.util.Properties)5 Socket (java.net.Socket)4 SearchResult (javax.naming.directory.SearchResult)4 UnknownHostException (java.net.UnknownHostException)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 NamingEnumeration (javax.naming.NamingEnumeration)2 SearchControls (javax.naming.directory.SearchControls)2 InitialLdapContext (javax.naming.ldap.InitialLdapContext)2 LdapContext (javax.naming.ldap.LdapContext)2 JndiUtils.getInitialDirContext (com.facebook.presto.server.security.util.jndi.JndiUtils.getInitialDirContext)1 AuthenticationFailedException (com.google.gerrit.server.account.AuthenticationFailedException)1 LdapCtx (com.sun.jndi.ldap.LdapCtx)1