Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License.  You can
  * obtain a copy of the License at
  * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
  * or packager/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  *
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at packager/legal/LICENSE.txt.
  *
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  *
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [year] [name of copyright owner]"
  *
  * Contributor(s):
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  *
  *
  * This file incorporates work covered by the following copyright and
  * permission notice:
  *
  * Copyright 2004 The Apache Software Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.apache.tomcat.util.net.jsse;
 
 import java.io.*;
 import java.net.*;
 
 
 /*
   1. Make the JSSE's jars available, either as an installed
      extension (copy them into jre/lib/ext) or by adding
      them to the Tomcat classpath.
   2. keytool -genkey -alias tomcat -keyalg RSA
      Use "changeit" as password ( this is the default we use )
  */

SSL server socket factory. It _requires_ a valid RSA key and JSSE.

Author(s):
Harish Prabandham
Costin Manolache
Stefan Freyr Stefansson
EKR -- renamed to JSSESocketFactory
Jan Luehe
public class JSSE14SocketFactory  extends JSSESocketFactory {
    private static StringManager sm =
        StringManager.getManager("org.apache.tomcat.util.net.jsse.res");
    public JSSE14SocketFactory () {
    }

    
    
Reads the keystore and initializes the SSL socket factory.
    /* SJSAS 6439313
    void init() throws IOException{
     */
    // START SJSAS 6439313
    public void init() throws IOException{
    // END SJSAS 6439313
        try {
            String clientAuthStr = (String.get("clientauth");
            if (clientAuthStr != null){
                 = Boolean.valueOf(clientAuthStr).booleanValue();
            }
            // SSL protocol variant (e.g., TLS, SSL v3, etc.)
            String protocol = (String.get("protocol");
            if (protocol == null) {
                protocol = ;
            }
            // Certificate encoding algorithm (e.g., SunX509)
            String algorithm = (String.get("algorithm");
            if (algorithm == null) {
                algorithm = ;
            }
            // Create and init SSLContext
            /* SJSAS 6439313
            SSLContext context = SSLContext.getInstance(protocol);
             */
            
            // START SJSAS 6439313
             = SSLContext.getInstance(protocol);
            // END SJSAS 6439313 
            
            // Configure SSL session timeout and cache size
                
            String trustAlgorithm = (String).get("truststoreAlgorithm");
            if (trustAlgorithm == null) {
                trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            }
            .init(getKeyManagers(algorithm,
                                        (String.get("keyAlias")),
                         getTrustManagers(trustAlgorithm),
                         new SecureRandom());
            // create proxy
             = .getServerSocketFactory();
            // Determine which cipher suites to enable
            String requestedCiphers = (String).get("ciphers");
            if (requestedCiphers != null) {
                 = getEnabledCiphers(requestedCiphers,
                                                   .getSupportedCipherSuites());
            }
        } catch(Exception e) {
            ife instanceof IOException )
                throw (IOException)e;
            throw new IOException(e.getMessage());
        }
    }

    
Gets the initialized key managers.
    protected KeyManager[] getKeyManagers(String algorithm,
                                          String keyAlias)
                throws Exception {
        KeyManager[] kms = null;
        String keystorePass = getKeystorePassword();
        KeyStore ks = getKeystore(keystorePass);
        if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
            throw new IOException(.getString("jsse.alias_no_key_entry"keyAlias));
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(kskeystorePass.toCharArray());
        kms = kmf.getKeyManagers();
        if (keyAlias != null) {
            // START SJSAS 6266949
            /*
            if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
                keyAlias = keyAlias.toLowerCase();
            }
            */
            //END SJSAS 6266949
            
            for(int i=0; i<kms.lengthi++) {
                kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], keyAlias);
            }
        }
        return kms;
    }

    
Gets the intialized trust managers.
    protected TrustManager[] getTrustManagers(String algorithm)
                throws Exception {
        String crlf = (String.get("crlFile");
        TrustManager[] tms = null;
        KeyStore trustStore = getTrustStore();
        if (trustStore != null) {
            if (crlf == null) {
                TrustManagerFactory tmf =
                    TrustManagerFactory.getInstance(algorithm);
                tmf.init(trustStore);
                tms = tmf.getTrustManagers();
            } else {
                TrustManagerFactory tmf =
                    TrustManagerFactory.getInstance(algorithm);
                CertPathParameters params = getParameters(algorithmcrlf,
                                                          trustStore);
                ManagerFactoryParameters mfp = 
                    new CertPathTrustManagerParameters(params);
                tmf.init(mfp);
                tms = tmf.getTrustManagers();
            }
        }
        return tms;
    }


    
Return the initialization parameters for the TrustManager. Currently, only the default PKIX is supported.

Parameters:
algorithm The algorithm to get parameters for.
crlf The path to the CRL file.
trustStore The configured TrustStore.
Returns:
The parameters including the CRLs and TrustStore.
    protected CertPathParameters getParameters(String algorithm
                                               String crlf
                                               KeyStore trustStore)
            throws Exception {
        CertPathParameters params = null;
        if ("PKIX".equalsIgnoreCase(algorithm)) {
            PKIXBuilderParameters xparams =
                new PKIXBuilderParameters(trustStore
                                          new X509CertSelector());
            Collection crls = getCRLs(crlf);
            CertStoreParameters csp = new CollectionCertStoreParameters(crls);
            CertStore store = CertStore.getInstance("Collection"csp);
            xparams.addCertStore(store);
            xparams.setRevocationEnabled(true);
            String trustLength = (String).get("trustMaxCertLength");
            if (trustLength != null) {
                try {
                    xparams.setMaxPathLength(Integer.parseInt(trustLength));
                } catch(Exception ex) {
                    .warn("Bad maxCertLength: " + trustLength);
                }
            }
            params = xparams;
        } else {
            throw new CRLException("CRLs not supported for type: "
                                   + algorithm);
        }
        return params;
    }


    
Load the collection of CRLs.
    protected Collection<? extends CRLgetCRLs(String crlf
            throws IOExceptionCRLExceptionCertificateException {
        File crlFile = new File(crlf);
        if (!crlFile.isAbsolute()) {
            crlFile = new File(System.getProperty("catalina.base"), crlf);
        }
        Collection<? extends CRLcrls = null;
        InputStream is = null;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            is = new FileInputStream(crlFile);
            crls = cf.generateCRLs(is);
        } catch(IOException iex) {
            throw iex;
        } catch(CRLException crle) {
            throw crle;
        } catch(CertificateException ce) {
            throw ce;
        } finally { 
            if (is != null) {
                try {
                    is.close();
                } catch (Exception ex) {
                }
            }
        }
        return crls;
    }
    protected void setEnabledProtocols(SSLServerSocket socketString []protocols){
        if (protocols != null) {
            socket.setEnabledProtocols(protocols);
        }
    }
    protected String[] getEnabledProtocols(SSLServerSocket socket,
                                           String requestedProtocols){
        String[] supportedProtocols = socket.getSupportedProtocols();
        String[] enabledProtocols = null;
        if (requestedProtocols != null) {
            Vector vec = null;
            String protocol = requestedProtocols;
            int index = requestedProtocols.indexOf(',');
            if (index != -1) {
                int fromIndex = 0;
                while (index != -1) {
                    protocol = requestedProtocols.substring(fromIndexindex).trim();
                    if (protocol.length() > 0) {
                        /*
                         * Check to see if the requested protocol is among the
                         * supported protocols, i.e., may be enabled
                         */
                        for (int i=0; supportedProtocols != null
                                     && i<supportedProtocols.lengthi++) {
                            if (supportedProtocols[i].equals(protocol)) {
                                if (vec == null) {
                                    vec = new Vector();
                                }
                                vec.addElement(protocol);
                                break;
                            }
                        }
                    }
                    fromIndex = index+1;
                    index = requestedProtocols.indexOf(','fromIndex);
                } // while
                protocol = requestedProtocols.substring(fromIndex);
            }
            if (protocol != null) {
                protocol = protocol.trim();
                if (protocol.length() > 0) {
                    /*
                     * Check to see if the requested protocol is among the
                     * supported protocols, i.e., may be enabled
                     */
                    for (int i=0; supportedProtocols != null
                                 && i<supportedProtocols.lengthi++) {
                        if (supportedProtocols[i].equals(protocol)) {
                            if (vec == null) {
                                vec = new Vector();
                            }
                            vec.addElement(protocol);
                            break;
                        }
                    }
                }
            }           
            if (vec != null) {
                enabledProtocols = new String[vec.size()];
                vec.copyInto(enabledProtocols);
            }
        }
        return enabledProtocols;
    }
    /*
     * Configures the given SSLSessionContext.
     *
     * @param sslSessionCtxt The SSLSessionContext to configure
     */
    private void configureSSLSessionContext(SSLSessionContext sslSessionCtxt) {
        String attrValue = (String.get("sslSessionTimeout");
        if (attrValue != null) {
            sslSessionCtxt.setSessionTimeout(
                Integer.valueOf(attrValue).intValue());
        }
        attrValue = (String.get("ssl3SessionTimeout");
        if (attrValue != null) {
            sslSessionCtxt.setSessionTimeout(
                Integer.valueOf(attrValue).intValue());
        }
     
        attrValue = (String.get("sslSessionCacheSize");
        if (attrValue != null) {
            sslSessionCtxt.setSessionCacheSize(
                Integer.valueOf(attrValue).intValue());
        }
    }
New to GrepCode? Check out our FAQ X