/
SSLContextBuilder.scala
381 lines (311 loc) · 13.8 KB
/
SSLContextBuilder.scala
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
/*
* Copyright (C) 2015 Typesafe Inc. <http://www.typesafe.com>
*/
package com.typesafe.sslconfig.ssl
import java.io._
import java.net.URL
import java.security._
import java.security.cert._
import com.typesafe.sslconfig.util.LoggerFactory
import javax.net.ssl._
trait SSLContextBuilder {
def build(): SSLContext
}
/**
* A simple SSL context builder. If the keyManagers or trustManagers are empty, then null is used in the init method.
* Likewise, if secureRandom is None then null is used.
*/
class SimpleSSLContextBuilder(protocol: String,
keyManagers: Seq[KeyManager],
trustManagers: Seq[TrustManager],
secureRandom: Option[SecureRandom]) extends SSLContextBuilder {
def nullIfEmpty[T](array: Array[T]) = {
if (array.isEmpty) null else array
}
/**
* Builds the appropriate SSL context manager.
*
* @return a configured SSL context.
*/
def build(): SSLContext = {
// We deliberately do not pass in a provider, on the recommendation of
// http://docs.oracle.com/javase/7/docs/technotes/guides/security/SunProviders.html#SunJSSEProvider
//
// "REMINDER: Cryptographic implementations in the JDK are distributed through several different providers
// ("Sun", "SunJSSE", "SunJCE", "SunRsaSign") for both historical reasons and by the types of services provided.
// General purpose applications SHOULD NOT request cryptographic services from specific providers."
val sslContext = SSLContext.getInstance(protocol)
sslContext.init(nullIfEmpty(keyManagers.toArray), nullIfEmpty(trustManagers.toArray), secureRandom.orNull)
sslContext
}
}
// the KeyManagerFactory and TrustManagerFactory use final methods and protected abstract constructors that make
// mocking tough. Either we provide a wrapper, or we set up our own "mock" provider, or we use Powermock.
trait KeyManagerFactoryWrapper {
@throws[KeyStoreException]
@throws[NoSuchAlgorithmException]
@throws[UnrecoverableKeyException]
def init(keystore: KeyStore, password: Array[Char]): Unit
def getKeyManagers: Array[KeyManager]
}
trait TrustManagerFactoryWrapper {
@throws[InvalidAlgorithmParameterException]
def init(spec: ManagerFactoryParameters): Unit
def getTrustManagers: Array[TrustManager]
}
class DefaultKeyManagerFactoryWrapper(keyManagerAlgorithm: String) extends KeyManagerFactoryWrapper {
private val instance = KeyManagerFactory.getInstance(keyManagerAlgorithm)
def init(keystore: KeyStore, password: Array[Char]): Unit = {
instance.init(keystore, password)
}
def getKeyManagers: Array[KeyManager] = instance.getKeyManagers
}
class DefaultTrustManagerFactoryWrapper(trustManagerAlgorithm: String) extends TrustManagerFactoryWrapper {
private val instance = TrustManagerFactory.getInstance(trustManagerAlgorithm)
def init(spec: ManagerFactoryParameters): Unit = {
instance.init(spec)
}
def getTrustManagers: Array[TrustManager] = instance.getTrustManagers
}
/**
* Creates an SSL context builder from info objects.
*/
class ConfigSSLContextBuilder(mkLogger: LoggerFactory,
info: SSLConfigSettings,
keyManagerFactory: KeyManagerFactoryWrapper,
trustManagerFactory: TrustManagerFactoryWrapper) extends SSLContextBuilder {
protected val logger = mkLogger(getClass)
def build(): SSLContext = {
val revocationLists = certificateRevocationList(info)
val signatureConstraints = info.disabledSignatureAlgorithms.map(AlgorithmConstraintsParser.apply).toSet
val keySizeConstraints = info.disabledKeyAlgorithms.map(AlgorithmConstraintsParser.apply).toSet
val algorithmChecker = new AlgorithmChecker(mkLogger, signatureConstraints, keySizeConstraints)
val keyManagers: Seq[KeyManager] = if (info.keyManagerConfig.keyStoreConfigs.nonEmpty) {
Seq(buildCompositeKeyManager(info.keyManagerConfig, algorithmChecker))
} else Nil
val trustManagers: Seq[TrustManager] = if (info.trustManagerConfig.trustStoreConfigs.nonEmpty) {
Seq(buildCompositeTrustManager(info.trustManagerConfig, info.checkRevocation.getOrElse(false), revocationLists, algorithmChecker))
} else Nil
buildSSLContext(info.protocol, keyManagers, trustManagers, info.secureRandom)
}
def buildSSLContext(protocol: String,
keyManagers: Seq[KeyManager],
trustManagers: Seq[TrustManager],
secureRandom: Option[SecureRandom]) = {
val builder = new SimpleSSLContextBuilder(protocol, keyManagers, trustManagers, secureRandom)
builder.build()
}
def buildCompositeKeyManager(keyManagerConfig: KeyManagerConfig, algorithmChecker: AlgorithmChecker) = {
val keyManagers = keyManagerConfig.keyStoreConfigs.map {
ksc =>
buildKeyManager(ksc, algorithmChecker)
}
new CompositeX509KeyManager(mkLogger, keyManagers)
}
def buildCompositeTrustManager(trustManagerInfo: TrustManagerConfig,
revocationEnabled: Boolean,
revocationLists: Option[Seq[CRL]], algorithmChecker: AlgorithmChecker) = {
val trustManagers = trustManagerInfo.trustStoreConfigs.map {
tsc =>
buildTrustManager(tsc, revocationEnabled, revocationLists, algorithmChecker)
}
new CompositeX509TrustManager(mkLogger, trustManagers, algorithmChecker)
}
// Get either a string or file based keystore builder from config.
def keyStoreBuilder(ksc: KeyStoreConfig): KeyStoreBuilder = {
val password = ksc.password.map(_.toCharArray)
ksc.filePath.map { f =>
if (ksc.isFileOnClasspath) {
fileOnClasspathBuilder(ksc.storeType, f, password)
} else {
fileBuilder(ksc.storeType, f, password)
}
}.getOrElse {
val data = ksc.data.getOrElse(throw new IllegalStateException("No keystore builder found!"))
stringBuilder(data)
}
}
def trustStoreBuilder(tsc: TrustStoreConfig): KeyStoreBuilder = {
tsc.filePath.map { f =>
if (tsc.isFileOnClasspath) {
fileOnClasspathBuilder(tsc.storeType, f, None)
} else {
fileBuilder(tsc.storeType, f, None)
}
}.getOrElse {
val data = tsc.data.getOrElse(throw new IllegalStateException("No truststore builder found!"))
stringBuilder(data)
}
}
def fileBuilder(storeType: String, filePath: String, password: Option[Array[Char]]): KeyStoreBuilder = {
new FileBasedKeyStoreBuilder(storeType, filePath, password)
}
def fileOnClasspathBuilder(storeType: String, filePath: String, password: Option[Array[Char]]): KeyStoreBuilder = {
new FileOnClasspathBasedKeyStoreBuilder(storeType, filePath, password)
}
def stringBuilder(data: String): KeyStoreBuilder = {
new StringBasedKeyStoreBuilder(data)
}
/**
* Returns true if the keystore should throw an exception as a result of the JSSE bug 6879539, false otherwise.
*/
def warnOnPKCS12EmptyPasswordBug(ksc: KeyStoreConfig): Boolean =
ksc.storeType.equalsIgnoreCase("pkcs12") && !ksc.password.exists(!_.isEmpty)
/**
* Builds a key manager from a keystore, using the KeyManagerFactory.
*/
def buildKeyManager(ksc: KeyStoreConfig, algorithmChecker: AlgorithmChecker): X509KeyManager = {
val keyStore = try {
keyStoreBuilder(ksc).build()
} catch {
case bpe: javax.crypto.BadPaddingException =>
// http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6415637
// http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6974037
// If you run into "Given final block not properly padded", then it's because you entered in the
// wrong password for the keystore, and JSSE tries to decrypt and only then verify the MAC.
throw new SecurityException("Mac verify error: invalid password?", bpe)
}
if (!validateStoreContainsPrivateKeys(ksc, keyStore)) {
logger.warn(s"Client authentication is not possible as there are no private keys found in ${ksc.filePath}")
}
validateStore(keyStore, algorithmChecker)
val password = ksc.password.map(_.toCharArray)
val factory = keyManagerFactory
try {
factory.init(keyStore, password.orNull)
} catch {
case e: UnrecoverableKeyException =>
logger.error(s"Unrecoverable key in keystore $ksc") // TODO log OR rethrow I'd suggest, any reason it's not?
throw new IllegalStateException(e)
}
val keyManagers = factory.getKeyManagers
if (keyManagers == null) {
val msg = s"Cannot create key manager with configuration $ksc"
throw new IllegalStateException(msg)
}
// The JSSE implementation only sends back ONE key manager, X509ExtendedKeyManager
keyManagers.head.asInstanceOf[X509KeyManager]
}
// Should anyone have any interest in implementing this feature at all, they can implement this method and
// submit a patch.
def certificateRevocationList(sslConfig: SSLConfigSettings): Option[Seq[CRL]] = {
sslConfig.revocationLists.map {
urls =>
urls.map(generateCRLFromURL)
}
}
def generateCRL(inputStream: InputStream): CRL = {
val cf = CertificateFactory.getInstance("X509")
val crl = cf.generateCRL(inputStream).asInstanceOf[X509CRL]
crl
}
def generateCRLFromURL(url: URL): CRL = {
val connection = url.openConnection()
connection.setDoInput(true)
connection.setUseCaches(false)
val inStream = new DataInputStream(connection.getInputStream)
try {
generateCRL(inStream)
} finally {
inStream.close()
}
}
def generateCRLFromFile(file: File): CRL = {
val fileStream = new BufferedInputStream(new FileInputStream(file))
val inStream = new DataInputStream(fileStream)
try {
generateCRL(inStream)
} finally {
inStream.close()
}
}
def buildTrustManagerParameters(trustStore: KeyStore,
revocationEnabled: Boolean,
revocationLists: Option[Seq[CRL]],
algorithmChecker: AlgorithmChecker): CertPathTrustManagerParameters = {
import scala.collection.JavaConverters._
val certSelect: X509CertSelector = new X509CertSelector
val pkixParameters = new PKIXBuilderParameters(trustStore, certSelect)
pkixParameters.setRevocationEnabled(revocationEnabled)
// For the sake of completeness, set the static revocation list if it exists...
revocationLists.map {
crlList =>
import scala.collection.JavaConverters._
pkixParameters.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crlList.asJavaCollection)))
}
// Add the algorithm checker in here to check the certification path sequence (not including trust anchor)...
val checkers: Seq[PKIXCertPathChecker] = Seq(algorithmChecker)
// Use the custom cert path checkers we defined...
pkixParameters.setCertPathCheckers(checkers.asJava)
new CertPathTrustManagerParameters(pkixParameters)
}
/**
* Builds trust managers, using a TrustManagerFactory internally.
*/
def buildTrustManager(tsc: TrustStoreConfig,
revocationEnabled: Boolean,
revocationLists: Option[Seq[CRL]], algorithmChecker: AlgorithmChecker): X509TrustManager = {
val factory = trustManagerFactory
val trustStore = trustStoreBuilder(tsc).build()
validateStore(trustStore, algorithmChecker)
val trustManagerParameters = buildTrustManagerParameters(
trustStore,
revocationEnabled,
revocationLists,
algorithmChecker)
factory.init(trustManagerParameters)
val trustManagers = factory.getTrustManagers
if (trustManagers == null) {
val msg = s"Cannot create trust manager with configuration $tsc"
throw new IllegalStateException(msg)
}
// The JSSE implementation only sends back ONE trust manager, X509TrustManager
trustManagers.head.asInstanceOf[X509TrustManager]
}
/**
* Validates that a key store (as opposed to a trust store) contains private keys for client authentication.
*/
def validateStoreContainsPrivateKeys(ksc: KeyStoreConfig, keyStore: KeyStore): Boolean = {
import scala.collection.JavaConverters._
// Is there actually a private key being stored in this key store?
val password = ksc.password.map(_.toCharArray).orNull
var containsPrivateKeys = false
for (keyAlias <- keyStore.aliases().asScala) {
val key = keyStore.getKey(keyAlias, password)
key match {
case privateKey: PrivateKey =>
logger.debug(s"validateStoreContainsPrivateKeys: private key found for alias $keyAlias")
containsPrivateKeys = true
case otherKey =>
// We want to warn on every failure, as this is not the correct setup for a key store.
val msg = s"validateStoreContainsPrivateKeys: No private key found for alias $keyAlias, it cannot be used for client authentication"
logger.warn(msg)
}
}
containsPrivateKeys
}
/**
* Tests each trusted certificate in the store, and warns if the certificate is not valid. Does not throw
* exceptions.
*/
def validateStore(store: KeyStore, algorithmChecker: AlgorithmChecker): Unit = {
import scala.collection.JavaConverters._
logger.debug(s"validateStore: type = ${store.getType}, size = ${store.size}")
store.aliases().asScala.foreach {
alias =>
Option(store.getCertificate(alias)).map {
c =>
try {
algorithmChecker.checkKeyAlgorithms(c)
} catch {
case e: CertPathValidatorException =>
logger.warn(s"validateStore: Skipping certificate with weak key size in $alias: " + e.getMessage)
store.deleteEntry(alias)
case e: Exception =>
logger.warn(s"validateStore: Skipping unknown exception $alias: " + e.getMessage)
store.deleteEntry(alias)
}
}
}
}
}