View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.http.conn.ssl;
29  
30  import java.net.Socket;
31  import java.security.KeyManagementException;
32  import java.security.KeyStore;
33  import java.security.KeyStoreException;
34  import java.security.NoSuchAlgorithmException;
35  import java.security.Principal;
36  import java.security.PrivateKey;
37  import java.security.SecureRandom;
38  import java.security.UnrecoverableKeyException;
39  import java.security.cert.CertificateException;
40  import java.security.cert.X509Certificate;
41  import java.util.HashMap;
42  import java.util.HashSet;
43  import java.util.Map;
44  import java.util.Set;
45  
46  import javax.net.ssl.KeyManager;
47  import javax.net.ssl.KeyManagerFactory;
48  import javax.net.ssl.SSLContext;
49  import javax.net.ssl.TrustManager;
50  import javax.net.ssl.TrustManagerFactory;
51  import javax.net.ssl.X509KeyManager;
52  import javax.net.ssl.X509TrustManager;
53  
54  import org.apache.http.annotation.NotThreadSafe;
55  
56  /**
57   * Builder for {@link SSLContext} instances.
58   *
59   * @since 4.3
60   */
61  @NotThreadSafe
62  public class SSLContextBuilder {
63  
64      static final String TLS   = "TLS";
65      static final String SSL   = "SSL";
66  
67      private String protocol;
68      private Set<KeyManager> keymanagers;
69      private Set<TrustManager> trustmanagers;
70      private SecureRandom secureRandom;
71  
72      public SSLContextBuilder() {
73          super();
74          this.keymanagers = new HashSet<KeyManager>();
75          this.trustmanagers = new HashSet<TrustManager>();
76      }
77  
78      public SSLContextBuilder useTLS() {
79          this.protocol = TLS;
80          return this;
81      }
82  
83      public SSLContextBuilder useSSL() {
84          this.protocol = SSL;
85          return this;
86      }
87  
88      public SSLContextBuilder useProtocol(final String protocol) {
89          this.protocol = protocol;
90          return this;
91      }
92  
93      public SSLContextBuilder setSecureRandom(final SecureRandom secureRandom) {
94          this.secureRandom = secureRandom;
95          return this;
96      }
97  
98      public SSLContextBuilder loadTrustMaterial(
99              final KeyStore truststore,
100             final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {
101         final TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
102                 TrustManagerFactory.getDefaultAlgorithm());
103         tmfactory.init(truststore);
104         final TrustManager[] tms = tmfactory.getTrustManagers();
105         if (tms != null) {
106             if (trustStrategy != null) {
107                 for (int i = 0; i < tms.length; i++) {
108                     final TrustManager tm = tms[i];
109                     if (tm instanceof X509TrustManager) {
110                         tms[i] = new TrustManagerDelegate(
111                                 (X509TrustManager) tm, trustStrategy);
112                     }
113                 }
114             }
115             for (final TrustManager tm : tms) {
116                 this.trustmanagers.add(tm);
117             }
118         }
119         return this;
120     }
121 
122     public SSLContextBuilder loadTrustMaterial(
123             final KeyStore truststore) throws NoSuchAlgorithmException, KeyStoreException {
124         return loadTrustMaterial(truststore, null);
125     }
126 
127     public SSLContextBuilder loadKeyMaterial(
128             final KeyStore keystore,
129             final char[] keyPassword)
130                 throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
131         loadKeyMaterial(keystore, keyPassword, null);
132         return this;
133     }
134 
135     public SSLContextBuilder loadKeyMaterial(
136             final KeyStore keystore,
137             final char[] keyPassword,
138             final PrivateKeyStrategy aliasStrategy)
139             throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
140         final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
141                 KeyManagerFactory.getDefaultAlgorithm());
142         kmfactory.init(keystore, keyPassword);
143         final KeyManager[] kms =  kmfactory.getKeyManagers();
144         if (kms != null) {
145             if (aliasStrategy != null) {
146                 for (int i = 0; i < kms.length; i++) {
147                     final KeyManager km = kms[i];
148                     if (km instanceof X509KeyManager) {
149                         kms[i] = new KeyManagerDelegate(
150                                 (X509KeyManager) km, aliasStrategy);
151                     }
152                 }
153             }
154             for (final KeyManager km : kms) {
155                 keymanagers.add(km);
156             }
157         }
158         return this;
159     }
160 
161     public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException {
162         final SSLContext sslcontext = SSLContext.getInstance(
163                 this.protocol != null ? this.protocol : TLS);
164         sslcontext.init(
165                 !keymanagers.isEmpty() ? keymanagers.toArray(new KeyManager[keymanagers.size()]) : null,
166                 !trustmanagers.isEmpty() ? trustmanagers.toArray(new TrustManager[trustmanagers.size()]) : null,
167                 secureRandom);
168         return sslcontext;
169     }
170 
171     static class TrustManagerDelegate implements X509TrustManager {
172 
173         private final X509TrustManager trustManager;
174         private final TrustStrategy trustStrategy;
175 
176         TrustManagerDelegate(final X509TrustManager trustManager, final TrustStrategy trustStrategy) {
177             super();
178             this.trustManager = trustManager;
179             this.trustStrategy = trustStrategy;
180         }
181 
182         @Override
183         public void checkClientTrusted(
184                 final X509Certificate[] chain, final String authType) throws CertificateException {
185             this.trustManager.checkClientTrusted(chain, authType);
186         }
187 
188         @Override
189         public void checkServerTrusted(
190                 final X509Certificate[] chain, final String authType) throws CertificateException {
191             if (!this.trustStrategy.isTrusted(chain, authType)) {
192                 this.trustManager.checkServerTrusted(chain, authType);
193             }
194         }
195 
196         @Override
197         public X509Certificate[] getAcceptedIssuers() {
198             return this.trustManager.getAcceptedIssuers();
199         }
200 
201     }
202 
203     static class KeyManagerDelegate implements X509KeyManager {
204 
205         private final X509KeyManager keyManager;
206         private final PrivateKeyStrategy aliasStrategy;
207 
208         KeyManagerDelegate(final X509KeyManager keyManager, final PrivateKeyStrategy aliasStrategy) {
209             super();
210             this.keyManager = keyManager;
211             this.aliasStrategy = aliasStrategy;
212         }
213 
214         @Override
215         public String[] getClientAliases(
216                 final String keyType, final Principal[] issuers) {
217             return this.keyManager.getClientAliases(keyType, issuers);
218         }
219 
220         @Override
221         public String chooseClientAlias(
222                 final String[] keyTypes, final Principal[] issuers, final Socket socket) {
223             final Map<String, PrivateKeyDetails> validAliases = new HashMap<String, PrivateKeyDetails>();
224             for (final String keyType: keyTypes) {
225                 final String[] aliases = this.keyManager.getClientAliases(keyType, issuers);
226                 if (aliases != null) {
227                     for (final String alias: aliases) {
228                         validAliases.put(alias,
229                                 new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias)));
230                     }
231                 }
232             }
233             return this.aliasStrategy.chooseAlias(validAliases, socket);
234         }
235 
236         @Override
237         public String[] getServerAliases(
238                 final String keyType, final Principal[] issuers) {
239             return this.keyManager.getServerAliases(keyType, issuers);
240         }
241 
242         @Override
243         public String chooseServerAlias(
244                 final String keyType, final Principal[] issuers, final Socket socket) {
245             final Map<String, PrivateKeyDetails> validAliases = new HashMap<String, PrivateKeyDetails>();
246             final String[] aliases = this.keyManager.getServerAliases(keyType, issuers);
247             if (aliases != null) {
248                 for (final String alias: aliases) {
249                     validAliases.put(alias,
250                             new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias)));
251                 }
252             }
253             return this.aliasStrategy.chooseAlias(validAliases, socket);
254         }
255 
256         @Override
257         public X509Certificate[] getCertificateChain(final String alias) {
258             return this.keyManager.getCertificateChain(alias);
259         }
260 
261         @Override
262         public PrivateKey getPrivateKey(final String alias) {
263             return this.keyManager.getPrivateKey(alias);
264         }
265 
266     }
267 
268 }