/
SSL.scala
82 lines (72 loc) · 2.85 KB
/
SSL.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
package lol.http
import scala.collection.JavaConverters._
import java.security.KeyStore
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.{KeyManagerFactory, SNIHostName, SNIServerName, SSLContext, X509TrustManager}
import org.http4s.blaze.util.BogusKeystore
/** lol SSL. */
object SSL {
/** SSL configuration for clients. */
class ClientConfiguration private[http] (val ctx: SSLContext, name: String, hostname: String = "") {
def engine = {
val engine = ctx.createSSLEngine()
if(hostname != "") {
val sslParameters = engine.getSSLParameters()
val sniList = List(new SNIHostName(hostname): SNIServerName).asJava
sslParameters.setServerNames(sniList)
sslParameters.setEndpointIdentificationAlgorithm("HTTPS")
engine.setSSLParameters(sslParameters)
}
engine.setUseClientMode(true)
engine
}
override def toString = s"ClientConfiguration($name)"
}
/** SSL configuration for servers. */
class ServerConfiguration private[http] (val ctx: SSLContext, name: String) {
def engine = {
val engine = ctx.createSSLEngine()
engine.setUseClientMode(false)
engine
}
override def toString = s"ServerConfiguration($name)"
}
/** Provides the default client SSL configuration. */
object ClientConfiguration {
/** The default SSL configuration. */
implicit lazy val default = new ClientConfiguration({
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(null, null, null)
sslContext
}, "default")
}
/** A "Trust all" client configuration that will accept any certificate.
* You can use it as configuration for an HTTP client that need to connect to an
* insecure server.
*/
lazy val trustAll = new ClientConfiguration({
val sslContext = SSLContext.getInstance("TLS")
val trustAllCerts =
new X509TrustManager() {
def getAcceptedIssuers() = new Array[X509Certificate](0)
def checkClientTrusted(certs: Array[X509Certificate], authType: String) = ()
def checkServerTrusted(certs: Array[X509Certificate], authType: String) = ()
}
sslContext.init(null, Array(trustAllCerts), new SecureRandom())
sslContext
}, "trustAll")
/** An SSL server configuration with a self-signed certificate.
* You can use it to start an HTTPS server with an insecure certificate.
*/
lazy val selfSigned = new ServerConfiguration({
val ksStream = BogusKeystore.asInputStream()
val ks = KeyStore.getInstance("JKS")
ks.load(ksStream, BogusKeystore.getKeyStorePassword)
val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
kmf.init(ks, BogusKeystore.getCertificatePassword)
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(kmf.getKeyManagers(), null, null)
sslContext
}, "selfSigned")
}