Package javax.naming.ldap

Examples of javax.naming.ldap.StartTlsResponse


        }
        Hashtable env = new Hashtable(5, 0.75f);
        env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
        env.put(Context.PROVIDER_URL, "ldap://" + ldapHost
                + ((ldapPort == null) ? "" : (":" + ldapPort)));
        StartTlsResponse tlsResponse = null;
        LdapContext ctx = null;

        try {
            ctx = new InitialLdapContext(env, null);

            if (tls) {
                // Requesting to start TLS on an LDAP association
                tlsResponse = (StartTlsResponse) ctx.extendedOperation(
                        new StartTlsRequest());

                // Starting TLS
                tlsResponse.negotiate();
            }

            // A TLS/SSL secure channel has been established if you reach here.

            // Assertion of client's authorization Identity -- Explicit way
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, mechanism);
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL,
                  ((principalTemplate == null)
                  ? userName
                  : principalTemplate.replace("${username}", userName)));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
            if (saslRealm != null) {
                env.put("java.naming.security.sasl.realm", saslRealm);
            }

            // The Context.SECURITY_* authorizations are only applied when the
            // following statement executes.  (Or any other remote operations done
            // while the TLS connection is still open).
            NamingEnumeration<SearchResult> sRess = null;
            try {
                sRess = ctx.search(parentDn,
                        new BasicAttributes(rdnAttribute, userName),
                        attributeUnion);
            } catch (AuthenticationException ae) {
                throw new DenyException();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (!sRess.hasMore()) {
                throw new DenyException();
            }
            SearchResult sRes = sRess.next();
            if (sRess.hasMore()) {
                throw new RuntimeException("> 1 result");
            }
            Attributes attrs = sRes.getAttributes();
            if (accessAttribute != null) {
                Attribute attribute =  attrs.get(accessAttribute);
                if (attribute == null) {
                    throw new DenyException();
                }
                if (attribute.size() != 1) {
                    throw new RuntimeException("Access attribute '"
                            + accessAttribute + "' has unexpected value count: "
                            + attribute.size());
                }
                if (accessValuePattern != null) {
                    Object accessValue = attribute.get(0);
                    if (accessValue == null) {
                        throw new RuntimeException(
                                "Access Attr. value is null");
                    }
                    if (!(accessValue instanceof String)) {
                        throw new RuntimeException("Access Attr. value "
                                + "not a String: "
                                + accessValue.getClass().getName());
                    }
                    if (!accessValuePattern.matcher(
                            (String) accessValue).matches()) {
                        throw new DenyException();
                    }
                }
            }
            if (rolesSchemaAttribute == null) {
                return null;
            }

            // If we reach here, then we definitely need to try to return a
            // list of roles + schema.
            List<String> returns = new ArrayList<String>();
            Attribute attribute =  attrs.get(rolesSchemaAttribute);
            if (attribute != null) {
                int valCount = attribute.size();
                Matcher matcher;
                Object oneVal;
                for (int i = 0; i < valCount; i++) {
                    oneVal = attribute.get(i);
                    if (oneVal == null) {
                        throw new RuntimeException(
                                "R/S Attr value #" + i + " is null");
                    }
                    if (!(oneVal instanceof String)) {
                        throw new RuntimeException(
                                "R/S Attr value #" + i + " not a String: "
                                + oneVal.getClass().getName());
                    }
                    if (roleSchemaValuePattern == null) {
                        returns.add((String) oneVal);
                    } else {
                        matcher = roleSchemaValuePattern.matcher(
                                (String) oneVal);
                        if (matcher.matches()) {
                            returns.add((matcher.groupCount() > 0)
                                    ? matcher.group(1)
                                    : (String) oneVal);
                        }
                    }
                }
            }
            if (returns.size() < 1) {
                if (accessAttribute == null) {
                    throw new DenyException();
                }
                return new String[0];
            }
            return returns.toArray(new String[0]);
        } catch (DenyException de) {
            // This throws a non-runtime Exception, which is handled as an
            // access denial instead of a system problem.
            throw de;
        } catch (RuntimeException re) {
            throw re;
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        } catch (NamingException ne) {
            throw new RuntimeException(ne);
        } finally {
            if (tlsResponse != null) try {
                tlsResponse.close();
            } catch (IOException ioe) {
                logger.error("Failed to close TLS Response", ioe);
            }
            if (ctx != null) try {
                ctx.close();
View Full Code Here


          if (debug) {
            Log.debug("LdapManager: ... StartTlsRequest");
          }

          // Perform a StartTLS extended operation
          StartTlsResponse tls = (StartTlsResponse)
            ctx.extendedOperation(new StartTlsRequest());

          /* Open a TLS connection (over the existing LDAP association) and
             get details of the negotiated TLS session: cipher suite,
             peer certificate, etc. */
          try {
            SSLSession session = tls.negotiate(new org.jivesoftware.util.SimpleSSLSocketFactory());
           
            ctx.setTlsResponse(tls);
            ctx.setSslSession(session);
           
            if (debug) {
              Log.debug("LdapManager: ... peer host: "
                  + session.getPeerHost()
                  + ", CipherSuite: " + session.getCipherSuite());
            }

            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL,
                userDN + "," + baseDN);
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
         
          } catch (java.io.IOException ex) {
            Log.error(ex.getMessage(), ex);
          }

        // make at least one lookup to check authorization
        lookupExistence(
            ctx,
            userDN + "," + baseDN,
            new String[] {usernameField});
            }
           
            if (debug) {
                Log.debug("LdapManager: ... context created successfully, returning.");
            }
        }
        catch (NamingException ne) {
            // If an alt baseDN is defined, attempt a lookup there.
            if (alternateBaseDN != null) {
                try {
                    if (ctx != null) {
                        ctx.close();
                    }
                }
                catch (Exception e) {
                    Log.error(e.getMessage(), e);
                }
                try {
                    // See if the user authenticates.
                    Hashtable<String, Object> env = new Hashtable<String, Object>();
                    // Use a custom initial context factory if specified. Otherwise, use the default.
                    env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
                    env.put(Context.PROVIDER_URL, getProviderURL(alternateBaseDN));
                    if (sslEnabled) {
                        env.put("java.naming.ldap.factory.socket", "org.jivesoftware.util.SimpleSSLSocketFactory");
                        env.put(Context.SECURITY_PROTOCOL, "ssl");
                    }
                   
                    /* If startTLS is requested we MUST NOT bind() before
                     * the secure connection has been established. */
                    if (!(startTlsEnabled && !sslEnabled)) {
                      env.put(Context.SECURITY_AUTHENTICATION, "simple");
                      env.put(Context.SECURITY_PRINCIPAL, userDN + "," + alternateBaseDN);
                      env.put(Context.SECURITY_CREDENTIALS, password);
                    }
                    // Specify timeout to be 10 seconds, only on non SSL since SSL connections
                    // break with a timemout.
                    if (!sslEnabled) {
                        env.put("com.sun.jndi.ldap.connect.timeout", "10000");
                    }
                    if (ldapDebugEnabled) {
                        env.put("com.sun.jndi.ldap.trace.ber", System.err);
                    }
                    if (followReferrals) {
                        env.put(Context.REFERRAL, "follow");
                    }
                    if (!followAliasReferrals) {
                        env.put("java.naming.ldap.derefAliases", "never");
                    }
                    if (debug) {
                        Log.debug("LdapManager: Created context values, attempting to create context...");
                    }
                    ctx = new JiveInitialLdapContext(env, null);
                   
                    if (startTlsEnabled && !sslEnabled) {
                     
                  if (debug) {
                    Log.debug("LdapManager: ... StartTlsRequest");
                  }

                  // Perform a StartTLS extended operation
                  StartTlsResponse tls = (StartTlsResponse)
                    ctx.extendedOperation(new StartTlsRequest());

                  /* Open a TLS connection (over the existing LDAP association) and
                     get details of the negotiated TLS session: cipher suite,
                     peer certificate, etc. */
                  try {
                    SSLSession session = tls.negotiate(new org.jivesoftware.util.SimpleSSLSocketFactory());
                   
                    ctx.setTlsResponse(tls);
                    ctx.setSslSession(session);
                   
                    if (debug) {
View Full Code Here

                    if ( useStartTLS )
                    {
                        try
                        {
                            StartTlsResponse tls = ( StartTlsResponse ) context
                                .extendedOperation( new StartTlsRequest() );
                            tls.setHostnameVerifier( new HostnameVerifier()
                            {
                                public boolean verify( String arg0, SSLSession arg1 )
                                {
                                    return true;
                                }
                            } );
                            tls.negotiate( new DummySSLSocketFactory() );

                        }
                        catch ( Exception e )
                        {
                            namingException = new NamingException( e.getMessage() != null ? e.getMessage()
View Full Code Here

        env.put( "java.naming.provider.url", "ldap://localhost:" + ldapServer.getPort() );
        env.put( "java.naming.security.principal", "uid=admin,ou=system" );
        env.put( "java.naming.security.credentials", "secret" );
        env.put( "java.naming.security.authentication", "simple" );
        LdapContext ctx = new InitialLdapContext( env, null );
        StartTlsResponse tls = ( StartTlsResponse ) ctx.extendedOperation( new StartTlsRequest() );
        tls.setHostnameVerifier( new HostnameVerifier() {
            public boolean verify( String hostname, SSLSession session )
            {
                return true;
            }
        } );
        tls.negotiate( BogusSSLContextFactory.getInstance( false ).getSocketFactory() );

        // create a new certificate
        String newIssuerDN = "cn=new_issuer_dn";
        String newSubjectDN = "cn=new_subject_dn";
        ServerEntry entry = ldapServer.getDirectoryService().getAdminSession().lookup(
            new DN( "uid=admin,ou=system" ) );
        TlsKeyGenerator.addKeyPair( entry, newIssuerDN, newSubjectDN, "RSA" );

        // now update the certificate (over the wire)
        ModificationItem[] mods = new ModificationItem[3];
        mods[0] = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(
            TlsKeyGenerator.PRIVATE_KEY_AT, entry.get( TlsKeyGenerator.PRIVATE_KEY_AT ).getBytes() ) );
        mods[1] = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(
            TlsKeyGenerator.PUBLIC_KEY_AT, entry.get( TlsKeyGenerator.PUBLIC_KEY_AT ).getBytes() ) );
        mods[2] = new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(
            TlsKeyGenerator.USER_CERTIFICATE_AT, entry.get( TlsKeyGenerator.USER_CERTIFICATE_AT ).getBytes() ) );
        ctx.modifyAttributes( "uid=admin,ou=system", mods );
        ctx.close();

        ldapServer.reloadSslContext();
       
        // create a new secure connection
        ctx = new InitialLdapContext( env, null );
        tls = ( StartTlsResponse ) ctx.extendedOperation( new StartTlsRequest() );
        tls.setHostnameVerifier( new HostnameVerifier() {
            public boolean verify( String hostname, SSLSession session )
            {
                return true;
            }
        } );
        tls.negotiate( BogusSSLContextFactory.getInstance( false ).getSocketFactory() );

        // check the received certificate, it must contain the updated server certificate
        X509Certificate[] lastReceivedServerCertificates = BogusTrustManagerFactory.lastReceivedServerCertificates;
        assertNotNull( lastReceivedServerCertificates );
        assertEquals( 1, lastReceivedServerCertificates.length );
View Full Code Here

                    if ( useStartTLS )
                    {
                        try
                        {
                            StartTlsResponse tls = ( StartTlsResponse ) context
                                .extendedOperation( new StartTlsRequest() );
                            tls.setHostnameVerifier( new HostnameVerifier()
                            {
                                public boolean verify( String arg0, SSLSession arg1 )
                                {
                                    return true;
                                }
                            } );
                            tls.negotiate( new DummySSLSocketFactory() );

                        }
                        catch ( Exception e )
                        {
                            namingException = new NamingException( e.getMessage() != null ? e.getMessage()
View Full Code Here

            LOG.debug( "About to get initial context" );
            LdapContext ctx = new InitialLdapContext( env, null );

            // Start TLS
            LOG.debug( "About send startTls extended operation" );
            StartTlsResponse tls = ( StartTlsResponse ) ctx.extendedOperation( new StartTlsRequest() );
            LOG.debug( "Extended operation issued" );
            tls.setHostnameVerifier( new HostnameVerifier()
            {
                public boolean verify( String hostname, SSLSession session )
                {
                    return true;
                }
            } );
            LOG.debug( "TLS negotion about to begin" );
            tls.negotiate( ReloadableSSLSocketFactory.getDefault() );

            search( ii, ctx );

            // Don't call tls.close(), sometimes it hangs in socket.read() operation:
            // Stack trace:
View Full Code Here

                    if ( useStartTLS )
                    {
                        try
                        {
                            StartTlsResponse tls = ( StartTlsResponse ) context
                                .extendedOperation( new StartTlsRequest() );
                            tls.setHostnameVerifier( new HostnameVerifier()
                            {
                                public boolean verify( String arg0, SSLSession arg1 )
                                {
                                    return true;
                                }
                            } );
                            tls.negotiate( new DummySSLSocketFactory() );

                        }
                        catch ( Exception e )
                        {
                            this.namingException = new NamingException( e.getMessage() != null ? e.getMessage()
View Full Code Here

                    if ( useStartTLS )
                    {
                        try
                        {
                            StartTlsResponse tls = ( StartTlsResponse ) context
                                .extendedOperation( new StartTlsRequest() );
                            tls.setHostnameVerifier( new HostnameVerifier()
                            {
                                public boolean verify( String arg0, SSLSession arg1 )
                                {
                                    return true;
                                }
                            } );
                            tls.negotiate( new DummySSLSocketFactory() );

                        }
                        catch ( Exception e )
                        {
                            namingException = new NamingException( e.getMessage() != null ? e.getMessage()
View Full Code Here

                    if ( useStartTLS )
                    {
                        try
                        {
                            StartTlsResponse tls = ( StartTlsResponse ) context
                                .extendedOperation( new StartTlsRequest() );
                            tls.setHostnameVerifier( new HostnameVerifier()
                            {
                                public boolean verify( String arg0, SSLSession arg1 )
                                {
                                    return true;
                                }
                            } );
                            tls.negotiate( new DummySSLSocketFactory() );

                        }
                        catch ( Exception e )
                        {
                            namingException = new NamingException( e.getMessage() != null ? e.getMessage()
View Full Code Here

        }
        Hashtable env = new Hashtable(5, 0.75f);
        env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
        env.put(Context.PROVIDER_URL, "ldap://" + ldapHost
                + ((ldapPort == null) ? "" : (":" + ldapPort)));
        StartTlsResponse tlsResponse = null;
        LdapContext ctx = null;

        try {
            ctx = new InitialLdapContext(env, null);

            if (tls) {
                // Requesting to start TLS on an LDAP association
                tlsResponse = (StartTlsResponse) ctx.extendedOperation(
                        new StartTlsRequest());

                // Starting TLS
                tlsResponse.negotiate();
            }

            // A TLS/SSL secure channel has been established if you reach here.
         
            // Assertion of client's authorization Identity -- Explicit way
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, mechanism);
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL,
                  ((principalTemplate == null)
                  ? userName
                  : principalTemplate.replace("${username}", userName)));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
            if (saslRealm != null) {
                env.put("java.naming.security.sasl.realm", saslRealm);
            }
         
            // The Context.SECURITY_* authorizations are only applied when the
            // following statement executes.  (Or any other remote operations done
            // while the TLS connection is still open).
            NamingEnumeration<SearchResult> sRess = null;
            try {
                sRess = ctx.search(parentDn,
                        new BasicAttributes(rdnAttribute, userName),
                        attributeUnion);
            } catch (AuthenticationException ae) {
                throw new DenyException();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (!sRess.hasMore()) {
                throw new DenyException();
            }
            SearchResult sRes = sRess.next();
            if (sRess.hasMore()) {
                throw new RuntimeException("> 1 result");
            }
            Attributes attrs = sRes.getAttributes();
            if (accessAttribute != null) {
                Attribute attribute =  attrs.get(accessAttribute);
                if (attribute == null) {
                    throw new DenyException();
                }
                if (attribute.size() != 1) {
                    throw new RuntimeException("Access attribute '"
                            + accessAttribute + "' has unexpected value count: "
                            + attribute.size());
                }
                if (accessValuePattern != null) {
                    Object accessValue = attribute.get(0);
                    if (accessValue == null) {
                        throw new RuntimeException(
                                "Access Attr. value is null");
                    }
                    if (!(accessValue instanceof String)) {
                        throw new RuntimeException("Access Attr. value "
                                + "not a String: "
                                + accessValue.getClass().getName());
                    }
                    if (!accessValuePattern.matcher(
                            (String) accessValue).matches()) {
                        throw new DenyException();
                    }
                }
            }
            if (rolesSchemaAttribute == null) {
                return null;
            }

            // If we reach here, then we definitely need to try to return a
            // list of roles + schema.
            List<String> returns = new ArrayList<String>();
            Attribute attribute =  attrs.get(rolesSchemaAttribute);
            if (attribute != null) {
                int valCount = attribute.size();
                Matcher matcher;
                Object oneVal;
                for (int i = 0; i < valCount; i++) {
                    oneVal = attribute.get(i);
                    if (oneVal == null) {
                        throw new RuntimeException(
                                "R/S Attr value #" + i + " is null");
                    }
                    if (!(oneVal instanceof String)) {
                        throw new RuntimeException(
                                "R/S Attr value #" + i + " not a String: "
                                + oneVal.getClass().getName());
                    }
                    if (roleSchemaValuePattern == null) {
                        returns.add((String) oneVal);
                    } else {
                        matcher = roleSchemaValuePattern.matcher(
                                (String) oneVal);
                        if (matcher.matches()) {
                            returns.add((matcher.groupCount() > 0)
                                    ? matcher.group(1)
                                    : (String) oneVal);
                        }
                    }
                }
            }
            if (returns.size() < 1) {
                if (accessAttribute == null) {
                    throw new DenyException();
                }
                return new String[0];
            }
            return returns.toArray(new String[0]);
        } catch (DenyException de) {
            // This throws a non-runtime Exception, which is handled as an
            // access denial instead of a system problem.
            throw de;
        } catch (RuntimeException re) {
            throw re;
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        } catch (NamingException ne) {
            throw new RuntimeException(ne);
        } finally {
            if (tlsResponse != null) try {
                tlsResponse.close();
            } catch (IOException ioe) {
                logger.error("Failed to close TLS Response", ioe);
            }
            if (ctx != null) try {
                ctx.close();
View Full Code Here

TOP

Related Classes of javax.naming.ldap.StartTlsResponse

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.