View Javadoc

1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package org.jboss.netty.handler.ssl;
18  
19  import org.jboss.netty.buffer.ChannelBuffer;
20  import org.jboss.netty.buffer.ChannelBufferInputStream;
21  
22  import javax.net.ssl.KeyManagerFactory;
23  import javax.net.ssl.SSLContext;
24  import javax.net.ssl.SSLException;
25  import javax.net.ssl.SSLSessionContext;
26  import java.io.File;
27  import java.security.KeyFactory;
28  import java.security.KeyStore;
29  import java.security.PrivateKey;
30  import java.security.Security;
31  import java.security.cert.Certificate;
32  import java.security.cert.CertificateFactory;
33  import java.security.spec.InvalidKeySpecException;
34  import java.security.spec.PKCS8EncodedKeySpec;
35  import java.util.ArrayList;
36  import java.util.Collections;
37  import java.util.List;
38  
39  /**
40   * A server-side {@link SslContext} which uses JDK's SSL/TLS implementation.
41   */
42  public final class JdkSslServerContext extends JdkSslContext {
43  
44      private final SSLContext ctx;
45      private final List<String> nextProtocols;
46  
47      /**
48       * Creates a new instance.
49       *
50       * @param certChainFile an X.509 certificate chain file in PEM format
51       * @param keyFile a PKCS#8 private key file in PEM format
52       */
53      public JdkSslServerContext(File certChainFile, File keyFile) throws SSLException {
54          this(certChainFile, keyFile, null);
55      }
56  
57      /**
58       * Creates a new instance.
59       *
60       * @param certChainFile an X.509 certificate chain file in PEM format
61       * @param keyFile a PKCS#8 private key file in PEM format
62       * @param keyPassword the password of the {@code keyFile}.
63       *                    {@code null} if it's not password-protected.
64       */
65      public JdkSslServerContext(File certChainFile, File keyFile, String keyPassword) throws SSLException {
66          this(null, certChainFile, keyFile, keyPassword, null, null, 0, 0);
67      }
68  
69      /**
70       * Creates a new instance.
71       *
72       * @param bufPool the buffer pool which will be used by this context.
73       *                {@code null} to use the default buffer pool.
74       * @param certChainFile an X.509 certificate chain file in PEM format
75       * @param keyFile a PKCS#8 private key file in PEM format
76       * @param keyPassword the password of the {@code keyFile}.
77       *                    {@code null} if it's not password-protected.
78       * @param ciphers the cipher suites to enable, in the order of preference.
79       *                {@code null} to use the default cipher suites.
80       * @param nextProtocols the application layer protocols to accept, in the order of preference.
81       *                      {@code null} to disable TLS NPN/ALPN extension.
82       * @param sessionCacheSize the size of the cache used for storing SSL session objects.
83       *                         {@code 0} to use the default value.
84       * @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
85       *                       {@code 0} to use the default value.
86       */
87      public JdkSslServerContext(
88              SslBufferPool bufPool,
89              File certChainFile, File keyFile, String keyPassword,
90              Iterable<String> ciphers, Iterable<String> nextProtocols,
91              long sessionCacheSize, long sessionTimeout) throws SSLException {
92  
93          super(bufPool, ciphers);
94  
95          if (certChainFile == null) {
96              throw new NullPointerException("certChainFile");
97          }
98          if (keyFile == null) {
99              throw new NullPointerException("keyFile");
100         }
101 
102         if (keyPassword == null) {
103             keyPassword = "";
104         }
105 
106         if (nextProtocols != null && nextProtocols.iterator().hasNext()) {
107             if (!JettyNpnSslEngine.isAvailable()) {
108                 throw new SSLException("NPN/ALPN unsupported: " + nextProtocols);
109             }
110 
111             List<String> list = new ArrayList<String>();
112             for (String p: nextProtocols) {
113                 if (p == null) {
114                     break;
115                 }
116                 list.add(p);
117             }
118 
119             this.nextProtocols = Collections.unmodifiableList(list);
120         } else {
121             this.nextProtocols = Collections.emptyList();
122         }
123 
124         String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
125         if (algorithm == null) {
126             algorithm = "SunX509";
127         }
128 
129         try {
130             KeyStore ks = KeyStore.getInstance("JKS");
131             ks.load(null, null);
132             CertificateFactory cf = CertificateFactory.getInstance("X.509");
133             KeyFactory rsaKF = KeyFactory.getInstance("RSA");
134             KeyFactory dsaKF = KeyFactory.getInstance("DSA");
135 
136             ChannelBuffer encodedKeyBuf = PemReader.readPrivateKey(keyFile);
137             byte[] encodedKey = new byte[encodedKeyBuf.readableBytes()];
138             encodedKeyBuf.readBytes(encodedKey);
139             PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(encodedKey);
140 
141             PrivateKey key;
142             try {
143                 key = rsaKF.generatePrivate(encodedKeySpec);
144             } catch (InvalidKeySpecException ignore) {
145                 key = dsaKF.generatePrivate(encodedKeySpec);
146             }
147 
148             List<Certificate> certChain = new ArrayList<Certificate>();
149             for (ChannelBuffer buf: PemReader.readCertificates(certChainFile)) {
150                 certChain.add(cf.generateCertificate(new ChannelBufferInputStream(buf)));
151             }
152 
153             ks.setKeyEntry("key", key, keyPassword.toCharArray(), certChain.toArray(new Certificate[certChain.size()]));
154 
155             // Set up key manager factory to use our key store
156             KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
157             kmf.init(ks, keyPassword.toCharArray());
158 
159             // Initialize the SSLContext to work with our key managers.
160             ctx = SSLContext.getInstance(PROTOCOL);
161             ctx.init(kmf.getKeyManagers(), null, null);
162 
163             SSLSessionContext sessCtx = ctx.getServerSessionContext();
164             if (sessionCacheSize > 0) {
165                 sessCtx.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE));
166             }
167             if (sessionTimeout > 0) {
168                 sessCtx.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE));
169             }
170         } catch (Exception e) {
171             throw new SSLException("failed to initialize the server-side SSL context", e);
172         }
173     }
174 
175     @Override
176     public boolean isClient() {
177         return false;
178     }
179 
180     @Override
181     public List<String> nextProtocols() {
182         return nextProtocols;
183     }
184 
185     @Override
186     public SSLContext context() {
187         return ctx;
188     }
189 }