-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
KeyManagerUtils.java
416 lines (354 loc) · 18.5 KB
/
KeyManagerUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/*
* Copyright 2019 Thunderberry.
*
* 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
*
* https://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 nl.altindag.ssl.util;
import nl.altindag.ssl.exception.GenericKeyManagerException;
import nl.altindag.ssl.exception.GenericKeyStoreException;
import nl.altindag.ssl.keymanager.AggregatedX509ExtendedKeyManager;
import nl.altindag.ssl.keymanager.DummyX509ExtendedKeyManager;
import nl.altindag.ssl.keymanager.HotSwappableX509ExtendedKeyManager;
import nl.altindag.ssl.keymanager.KeyManagerFactoryWrapper;
import nl.altindag.ssl.keymanager.LoggingX509ExtendedKeyManager;
import nl.altindag.ssl.keymanager.X509KeyManagerWrapper;
import nl.altindag.ssl.model.KeyStoreHolder;
import nl.altindag.ssl.util.internal.UriUtils;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509KeyManager;
import java.net.URI;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import static nl.altindag.ssl.util.internal.CollectorsUtils.toListAndThen;
import static nl.altindag.ssl.util.internal.CollectorsUtils.toUnmodifiableList;
import static nl.altindag.ssl.util.internal.ValidationUtils.GENERIC_EXCEPTION_MESSAGE;
import static nl.altindag.ssl.util.internal.ValidationUtils.requireNotEmpty;
import static nl.altindag.ssl.util.internal.ValidationUtils.requireNotNull;
/**
* @author Hakan Altindag
*/
public final class KeyManagerUtils {
private static final char[] DUMMY_PASSWORD = KeyStoreUtils.DUMMY_PASSWORD.toCharArray();
private KeyManagerUtils() {}
public static X509ExtendedKeyManager combine(X509KeyManager... keyManagers) {
return combine(Arrays.asList(keyManagers));
}
public static X509ExtendedKeyManager combine(List<? extends X509KeyManager> keyManagers) {
return KeyManagerUtils.keyManagerBuilder()
.withKeyManagers(keyManagers)
.build();
}
public static <T extends X509KeyManager> X509ExtendedKeyManager[] toArray(T keyManager) {
return new X509ExtendedKeyManager[]{KeyManagerUtils.wrapIfNeeded(keyManager)};
}
public static X509ExtendedKeyManager createKeyManager(KeyStoreHolder... keyStoreHolders) {
return Arrays.stream(keyStoreHolders)
.map(keyStoreHolder -> createKeyManager(keyStoreHolder.getKeyStore(), keyStoreHolder.getKeyPassword()))
.collect(toListAndThen(KeyManagerUtils::combine));
}
public static X509ExtendedKeyManager createKeyManager(KeyStore keyStore, char[] keyPassword) {
return createKeyManager(keyStore, keyPassword, KeyManagerFactory.getDefaultAlgorithm());
}
public static X509ExtendedKeyManager createKeyManager(KeyStore keyStore, char[] keyPassword, String keyManagerFactoryAlgorithm) {
try {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm);
return createKeyManager(keyStore, keyPassword, keyManagerFactory);
} catch (NoSuchAlgorithmException e) {
throw new GenericKeyManagerException(e);
}
}
public static X509ExtendedKeyManager createKeyManager(KeyStore keyStore, char[] keyPassword, String keyManagerFactoryAlgorithm, String securityProviderName) {
try {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm, securityProviderName);
return createKeyManager(keyStore, keyPassword, keyManagerFactory);
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
throw new GenericKeyManagerException(e);
}
}
public static X509ExtendedKeyManager createKeyManager(KeyStore keyStore, char[] keyPassword, String keyManagerFactoryAlgorithm, Provider securityProvider) {
try {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm, securityProvider);
return createKeyManager(keyStore, keyPassword, keyManagerFactory);
} catch (NoSuchAlgorithmException e) {
throw new GenericKeyManagerException(e);
}
}
public static X509ExtendedKeyManager createKeyManager(KeyStore keyStore, char[] keyPassword, KeyManagerFactory keyManagerFactory) {
try {
keyManagerFactory.init(keyStore, keyPassword);
return KeyManagerUtils.getKeyManager(keyManagerFactory);
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
throw new GenericKeyManagerException(e);
}
}
public static X509ExtendedKeyManager createKeyManager(KeyStore keyStore, Map<String, char[]> aliasToPassword) {
List<X509ExtendedKeyManager> keyManagers = new ArrayList<>();
for (Entry<String, char[]> entry : aliasToPassword.entrySet()) {
try {
String alias = entry.getKey();
char[] password = entry.getValue();
if (keyStore.isKeyEntry(alias)) {
Key key = keyStore.getKey(alias, password);
Certificate[] certificateChain = keyStore.getCertificateChain(alias);
KeyStore identityStore = KeyStoreUtils.createIdentityStore(key, password, certificateChain);
X509ExtendedKeyManager keyManager = KeyManagerUtils.createKeyManager(identityStore, password);
keyManagers.add(keyManager);
}
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
throw new GenericKeyManagerException(e);
}
}
requireNotEmpty(keyManagers, () -> new GenericKeyManagerException("Could not create any KeyManager from the given KeyStore, Alias and Password"));
return KeyManagerUtils.combine(keyManagers);
}
public static X509ExtendedKeyManager wrapIfNeeded(X509KeyManager keyManager) {
if (keyManager instanceof X509ExtendedKeyManager) {
return (X509ExtendedKeyManager) keyManager;
} else {
return new X509KeyManagerWrapper(keyManager);
}
}
public static KeyManagerFactory createKeyManagerFactory(KeyManager keyManager) {
return new KeyManagerFactoryWrapper(keyManager);
}
public static <T extends KeyManagerFactory> X509ExtendedKeyManager getKeyManager(T keyManagerFactory) {
return Arrays.stream(keyManagerFactory.getKeyManagers())
.filter(X509KeyManager.class::isInstance)
.map(X509KeyManager.class::cast)
.map(KeyManagerUtils::wrapIfNeeded)
.collect(toListAndThen(KeyManagerUtils::combine));
}
public static X509ExtendedKeyManager createDummyKeyManager() {
return DummyX509ExtendedKeyManager.getInstance();
}
public static X509ExtendedKeyManager createLoggingKeyManager(X509KeyManager keyManager) {
return new LoggingX509ExtendedKeyManager(KeyManagerUtils.wrapIfNeeded(keyManager));
}
/**
* Wraps the given KeyManager into an instance of a Hot Swappable KeyManager
* This type of KeyManager has the capability of swapping in and out different KeyManagers at runtime.
*
* @param keyManager To be wrapped KeyManager
* @return Swappable KeyManager
*/
public static X509ExtendedKeyManager createSwappableKeyManager(X509KeyManager keyManager) {
return new HotSwappableX509ExtendedKeyManager(KeyManagerUtils.wrapIfNeeded(keyManager));
}
/**
* Swaps the internal KeyManager instance with the given keyManager object.
* The baseKeyManager should be an instance of {@link HotSwappableX509ExtendedKeyManager}
* and can be created with {@link KeyManagerUtils#createSwappableKeyManager(X509KeyManager)}
*
* @param baseKeyManager an instance of {@link HotSwappableX509ExtendedKeyManager}
* @param newKeyManager to be injected instance of a KeyManager
* @throws GenericKeyManagerException if {@code baseKeyManager} is not instance of {@link HotSwappableX509ExtendedKeyManager}
*/
public static void swapKeyManager(X509KeyManager baseKeyManager, X509KeyManager newKeyManager) {
if (newKeyManager instanceof HotSwappableX509ExtendedKeyManager) {
throw new GenericKeyManagerException(
String.format("The newKeyManager should not be an instance of [%s]", HotSwappableX509ExtendedKeyManager.class.getName())
);
}
if (baseKeyManager instanceof HotSwappableX509ExtendedKeyManager
&& ((HotSwappableX509ExtendedKeyManager) baseKeyManager).getInnerKeyManager() instanceof LoggingX509ExtendedKeyManager) {
((HotSwappableX509ExtendedKeyManager) baseKeyManager).setKeyManager(
new LoggingX509ExtendedKeyManager(
KeyManagerUtils.wrapIfNeeded(newKeyManager)
)
);
} else if (baseKeyManager instanceof HotSwappableX509ExtendedKeyManager) {
((HotSwappableX509ExtendedKeyManager) baseKeyManager).setKeyManager(KeyManagerUtils.wrapIfNeeded(newKeyManager));
} else {
throw new GenericKeyManagerException(
String.format("The baseKeyManager is from the instance of [%s] and should be an instance of [%s].",
baseKeyManager.getClass().getName(),
HotSwappableX509ExtendedKeyManager.class.getName())
);
}
}
public static void addIdentityRoute(X509ExtendedKeyManager keyManager, String alias, String... hosts) {
addIdentityRoute(keyManager, alias, hosts, false);
}
public static void overrideIdentityRoute(X509ExtendedKeyManager keyManager, String alias, String... hosts) {
addIdentityRoute(keyManager, alias, hosts, true);
}
private static void addIdentityRoute(X509ExtendedKeyManager keyManager,
String alias,
String[] hosts,
boolean overrideExistingRouteEnabled) {
requireNotNull(keyManager, GENERIC_EXCEPTION_MESSAGE.apply("KeyManager"));
requireNotNull(alias, GENERIC_EXCEPTION_MESSAGE.apply("Alias"));
requireNotNull(keyManager, GENERIC_EXCEPTION_MESSAGE.apply("Host"));
if (keyManager instanceof AggregatedX509ExtendedKeyManager) {
AggregatedX509ExtendedKeyManager aggregatedX509ExtendedKeyManager = (AggregatedX509ExtendedKeyManager) keyManager;
Map<String, List<URI>> aliasToHosts = aggregatedX509ExtendedKeyManager.getIdentityRoute();
List<URI> uris = new ArrayList<>();
for (String host : hosts) {
URI uri = URI.create(host);
UriUtils.validate(uri);
uris.add(uri);
}
if (overrideExistingRouteEnabled && aliasToHosts.containsKey(alias)) {
aliasToHosts.get(alias).clear();
}
for (URI uri : uris) {
if (aliasToHosts.containsKey(alias)) {
aliasToHosts.get(alias).add(uri);
} else {
aliasToHosts.put(alias, new ArrayList<>(Collections.singleton(uri)));
}
}
} else {
throw new GenericKeyManagerException(String.format(
"KeyManager should be an instance of: [%s], but received: [%s]",
AggregatedX509ExtendedKeyManager.class.getName(),
keyManager.getClass().getName()));
}
}
public static Map<String, List<String>> getIdentityRoute(X509ExtendedKeyManager keyManager) {
requireNotNull(keyManager, GENERIC_EXCEPTION_MESSAGE.apply("KeyManager"));
if (keyManager instanceof AggregatedX509ExtendedKeyManager) {
return ((AggregatedX509ExtendedKeyManager) keyManager)
.getIdentityRoute()
.entrySet().stream()
.collect(Collectors.collectingAndThen(
Collectors.toMap(
Entry::getKey,
hosts -> hosts.getValue().stream()
.map(URI::toString)
.collect(toUnmodifiableList())),
Collections::unmodifiableMap)
);
} else {
throw new GenericKeyManagerException(String.format(
"KeyManager should be an instance of: [%s], but received: [%s]",
AggregatedX509ExtendedKeyManager.class.getName(),
keyManager.getClass().getName()));
}
}
private static List<X509ExtendedKeyManager> unwrapIfPossible(X509ExtendedKeyManager keyManager) {
if (keyManager instanceof AggregatedX509ExtendedKeyManager) {
List<X509ExtendedKeyManager> keyManagers = new ArrayList<>();
for (X509ExtendedKeyManager innerKeyManager : ((AggregatedX509ExtendedKeyManager) keyManager).getInnerKeyManagers()) {
List<X509ExtendedKeyManager> unwrappedKeyManagers = KeyManagerUtils.unwrapIfPossible(innerKeyManager);
keyManagers.addAll(unwrappedKeyManagers);
}
return keyManagers;
} else {
return Collections.singletonList(keyManager);
}
}
public static KeyManagerBuilder keyManagerBuilder() {
return new KeyManagerBuilder();
}
public static X509ExtendedKeyManager createKeyManager(PrivateKey privateKey, Certificate[] certificatesChain) {
String alias = CertificateUtils.generateAlias(certificatesChain[0]);
return createKeyManager(alias, privateKey, certificatesChain);
}
public static X509ExtendedKeyManager createKeyManager(String alias, PrivateKey privateKey, Certificate[] certificatesChain) {
try {
KeyStore keyStore = KeyStoreUtils.createKeyStore();
keyStore.setKeyEntry(alias, privateKey, DUMMY_PASSWORD, certificatesChain);
return KeyManagerUtils.createKeyManager(keyStore, DUMMY_PASSWORD);
} catch (KeyStoreException e) {
throw new GenericKeyStoreException(e);
}
}
public static final class KeyManagerBuilder {
private static final String EMPTY_KEY_MANAGER_EXCEPTION = "Input does not contain KeyManagers";
private final List<X509ExtendedKeyManager> keyManagers = new ArrayList<>();
private final Map<String, List<URI>> aliasToHost = new HashMap<>();
private boolean swappableKeyManagerEnabled = false;
private boolean loggingKeyManagerEnabled = false;
private KeyManagerBuilder() {}
@SafeVarargs
public final <T extends X509KeyManager> KeyManagerBuilder withKeyManagers(T... keyManagers) {
for (X509KeyManager keyManager : keyManagers) {
withKeyManager(keyManager);
}
return this;
}
public <T extends X509KeyManager> KeyManagerBuilder withKeyManagers(List<T> keyManagers) {
for (X509KeyManager keyManager : keyManagers) {
withKeyManager(keyManager);
}
return this;
}
public <T extends X509KeyManager> KeyManagerBuilder withKeyManager(T keyManager) {
this.keyManagers.add(KeyManagerUtils.wrapIfNeeded(keyManager));
return this;
}
public KeyManagerBuilder withIdentities(KeyStoreHolder... identities) {
return withIdentities(Arrays.asList(identities));
}
public KeyManagerBuilder withIdentities(List<KeyStoreHolder> identities) {
for (KeyStoreHolder identity : identities) {
this.keyManagers.add(KeyManagerUtils.createKeyManager(identity.getKeyStore(), identity.getKeyPassword()));
}
return this;
}
public <T extends KeyStore> KeyManagerBuilder withIdentity(T identity, char[] identityPassword, String keyManagerAlgorithm) {
this.keyManagers.add(KeyManagerUtils.createKeyManager(identity, identityPassword, keyManagerAlgorithm));
return this;
}
public KeyManagerBuilder withSwappableKeyManager(boolean swappableKeyManagerEnabled) {
this.swappableKeyManagerEnabled = swappableKeyManagerEnabled;
return this;
}
public KeyManagerBuilder withLoggingKeyManager(boolean loggingKeyManagerEnabled) {
this.loggingKeyManagerEnabled = loggingKeyManagerEnabled;
return this;
}
public KeyManagerBuilder withIdentityRoute(Map<String, List<URI>> aliasToHost) {
this.aliasToHost.putAll(aliasToHost);
return this;
}
public X509ExtendedKeyManager build() {
requireNotEmpty(keyManagers, () -> new GenericKeyManagerException(EMPTY_KEY_MANAGER_EXCEPTION));
X509ExtendedKeyManager baseKeyManager;
if (keyManagers.size() == 1) {
baseKeyManager = keyManagers.get(0);
} else {
baseKeyManager = keyManagers.stream()
.map(KeyManagerUtils::unwrapIfPossible)
.flatMap(Collection::stream)
.collect(toListAndThen(extendedKeyManagers -> new AggregatedX509ExtendedKeyManager(extendedKeyManagers, aliasToHost)));
}
if (loggingKeyManagerEnabled) {
baseKeyManager = KeyManagerUtils.createLoggingKeyManager(baseKeyManager);
}
if (swappableKeyManagerEnabled) {
baseKeyManager = KeyManagerUtils.createSwappableKeyManager(baseKeyManager);
}
return baseKeyManager;
}
}
}