java.security.cert.X509Certificate Scala Examples

The following examples show how to use java.security.cert.X509Certificate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: SSL.scala    From lolhttp   with Apache License 2.0 6 votes vote down vote up
package lol.http

import java.security.KeyStore
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.{SSLContext, KeyManagerFactory, X509TrustManager}


import org.http4s.blaze.util.BogusKeystore


  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")

} 
Example 2
Source File: Security.scala    From keycloak-benchmark   with Apache License 2.0 5 votes vote down vote up
package org.jboss.perf

import java.math.BigInteger
import java.security.spec.{PKCS8EncodedKeySpec, X509EncodedKeySpec}
import java.security._
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit

import org.keycloak.common.util.Base64
import sun.security.x509._

import scala.util.Random


object Security {
  // not really secure; gives deterministic numbers
  private val secureRandom = new SecureRandom(new SecureRandomSpi {
    val random = new Random(1234L)
    override def engineGenerateSeed(numBytes: Int): Array[Byte] = {
      val bytes = new Array[Byte](numBytes)
      random.nextBytes(bytes)
      bytes
    }

    override def engineSetSeed(seed: Array[Byte]) {}

    override def engineNextBytes(bytes: Array[Byte]) {
      random.nextBytes(bytes)
    }

  }, new SecureRandom().getProvider) {}
  private val algorithm = "RSA"
  private val signingAlgorithm = "SHA256WithRSA"
  private val keyPair: KeyPair = {
    val generator = KeyPairGenerator.getInstance(algorithm)
    generator.initialize(2048, secureRandom)
    generator.genKeyPair()
  }

  val PublicKey =  Base64.encodeBytes(KeyFactory.getInstance(algorithm).getKeySpec(keyPair.getPublic, classOf[X509EncodedKeySpec]).getEncoded)
  val PrivateKey = Base64.encodeBytes(KeyFactory.getInstance(algorithm).getKeySpec(keyPair.getPrivate, classOf[PKCS8EncodedKeySpec]).getEncoded)
  val Certificate = Base64.encodeBytes(generateCertificate("CN=Benchmark", keyPair).getEncoded)

  private def generateCertificate(dn: String, pair: KeyPair): X509Certificate = {
    val info = new X509CertInfo();
    val from = new java.util.Date();
    val to = new java.util.Date(from.getTime() + TimeUnit.DAYS.toMillis(365));
    val interval = new CertificateValidity(from, to);
    val sn = new BigInteger(64, secureRandom);
    val owner = new X500Name(dn);

    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
    info.set(X509CertInfo.SUBJECT, owner);
    info.set(X509CertInfo.ISSUER, owner);
//    Use following for Java < 1.8:
//    info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
//    info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
    info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
    info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
    var algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
    info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));

    // Sign the cert to identify the algorithm that's used.
    var cert = new X509CertImpl(info);
    cert.sign(pair.getPrivate, signingAlgorithm);

    // Update the algorith, and resign.
    algo = cert.get(X509CertImpl.SIG_ALG).asInstanceOf[AlgorithmId];
    info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
    cert = new X509CertImpl(info);
    cert.sign(pair.getPrivate, signingAlgorithm);
    return cert;
  }
} 
Example 3
Source File: Build.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
import play.dev.filewatch.FileWatchService
import play.sbt.run.toLoggerProxy
import sbt._

import javax.net.ssl.SSLContext
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
import java.security.cert.X509Certificate
import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer
import scala.util.Properties

// This is an almost verbatim copy from Play's
// https://github.com/playframework/playframework/blob/master/framework/src/sbt-plugin/src/sbt-test/play-sbt-plugin/generated-keystore/project/Build.scala
// I think some parts could be trimmed but keeping the (almost) verbatim copy will ease future consolidation.
// Changes compared to Play's version:
//  - had to replace `path` with `url` in `verifyResourceContains`
object DevModeBuild {

  def jdk7WatchService = Def.setting {
    FileWatchService.jdk7(Keys.sLog.value)
  }

  def jnotifyWatchService = Def.setting {
    FileWatchService.jnotify(Keys.target.value)
  }

  // Using 30 max attempts so that we can give more chances to
  // the file watcher service. This is relevant when using the
  // default JDK watch service which does uses polling.
  val MaxAttempts = 30
  val WaitTime    = 500L

  val ConnectTimeout = 10000
  val ReadTimeout    = 10000

  private val trustAllManager = {
    val manager = new X509TrustManager() {
      def getAcceptedIssuers: Array[X509Certificate]                                = null
      def checkClientTrusted(certs: Array[X509Certificate], authType: String): Unit = {}
      def checkServerTrusted(certs: Array[X509Certificate], authType: String): Unit = {}
    }
    Array[TrustManager](manager)
  }
  @tailrec
  def verifyResourceContains(
      url: String,
      status: Int,
      assertions: Seq[String],
      attempts: Int,
      headers: (String, String)*
  ): Unit = {
    println(s"Attempt $attempts at $url")
    val messages = ListBuffer.empty[String]
    try {
      val sc = SSLContext.getInstance("SSL")
      sc.init(null, trustAllManager, null)
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory)

      val jnUrl = new java.net.URL(url)
      val conn  = jnUrl.openConnection().asInstanceOf[java.net.HttpURLConnection]
      conn.setConnectTimeout(ConnectTimeout)
      conn.setReadTimeout(ReadTimeout)

      headers.foreach(h => conn.setRequestProperty(h._1, h._2))

      if (status == conn.getResponseCode) messages += s"Resource at $url returned $status as expected"
      else throw new RuntimeException(s"Resource at $url returned ${conn.getResponseCode} instead of $status")

      val is = if (conn.getResponseCode >= 400) conn.getErrorStream else conn.getInputStream

      // The input stream may be null if there's no body
      val contents = if (is != null) {
        val c = IO.readStream(is)
        is.close()
        c
      } else ""
      conn.disconnect()

      assertions.foreach { assertion =>
        if (contents.contains(assertion)) messages += s"Resource at $url contained $assertion"
        else throw new RuntimeException(s"Resource at $url didn't contain '$assertion':\n$contents")
      }

      messages.foreach(println)
    } catch {
      case e: Exception =>
        println(s"Got exception: $e")
        if (attempts < MaxAttempts) {
          Thread.sleep(WaitTime)
          verifyResourceContains(url, status, assertions, attempts + 1, headers: _*)
        } else {
          messages.foreach(println)
          println(s"After $attempts attempts:")
          throw e
        }
    }
  }
} 
Example 4
Source File: HttpClientProvider.scala    From reactive-nakadi   with MIT License 5 votes vote down vote up
package org.zalando.react.nakadi.client.providers

import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.{SSLContext, TrustManager, X509TrustManager}

import akka.actor.ActorContext
import akka.http.scaladsl.Http.OutgoingConnection
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.http.scaladsl.settings.ClientConnectionSettings
import akka.http.scaladsl.{Http, HttpsConnectionContext}
import akka.stream.scaladsl.Flow

import scala.concurrent.Future
import scala.concurrent.duration._


class HttpClientProvider(actorContext: ActorContext,
                         server: String, port: Int,
                         isConnectionSSL: Boolean = false,
                         acceptAnyCertificate: Boolean = false,
                         connectionTimeout: FiniteDuration) {

  val http = Http(actorContext.system)

  private val settings = {
    ClientConnectionSettings
      .apply(actorContext.system)
      .withConnectingTimeout(connectionTimeout)
      .withIdleTimeout(Duration.Inf)
  }

  val connection: Flow[HttpRequest, HttpResponse, Future[OutgoingConnection]] = {

    isConnectionSSL match {
      case true =>
        val sslContext = if (!acceptAnyCertificate) SSLContext.getDefault else {

          val permissiveTrustManager: TrustManager = new X509TrustManager() {
            override def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
            override def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
            override def getAcceptedIssuers(): Array[X509Certificate] = Array.empty
          }

          val ctx = SSLContext.getInstance("TLS")
          ctx.init(Array.empty, Array(permissiveTrustManager), new SecureRandom())
          ctx
        }
        http.outgoingConnectionHttps(server, port, new HttpsConnectionContext(sslContext), settings = settings)
      case false =>
        http.outgoingConnection(server, port, settings = settings)
    }
  }

} 
Example 5
Source File: SSLContextUtils.scala    From akka-grpc   with Apache License 2.0 5 votes vote down vote up
package akka.grpc

import java.io.{ BufferedInputStream, IOException, InputStream }
import java.security.KeyStore
import java.security.cert.{ CertificateFactory, X509Certificate }

import javax.net.ssl.{ TrustManager, TrustManagerFactory }

object SSLContextUtils {
  def trustManagerFromStream(certStream: InputStream): TrustManager = {
    try {
      import scala.collection.JavaConverters._
      val cf = CertificateFactory.getInstance("X.509")
      val bis = new BufferedInputStream(certStream)

      val keystore = KeyStore.getInstance(KeyStore.getDefaultType)
      keystore.load(null)
      cf.generateCertificates(bis).asScala.foreach { cert =>
        val alias = cert.asInstanceOf[X509Certificate].getSubjectX500Principal.getName
        keystore.setCertificateEntry(alias, cert)
      }

      val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
      tmf.init(keystore)
      tmf.getTrustManagers()(0)
    } finally certStream.close()
  }

  def trustManagerFromResource(certificateResourcePath: String): TrustManager = {
    val certStream: InputStream = getClass.getResourceAsStream(certificateResourcePath)
    if (certStream == null) throw new IOException(s"Couldn't find '$certificateResourcePath' on the classpath")
    trustManagerFromStream(certStream)
  }
} 
Example 6
Source File: SslContexts.scala    From kubernetes-client   with Apache License 2.0 5 votes vote down vote up
package com.goyeau.kubernetes.client.util
import java.io.{ByteArrayInputStream, File, FileInputStream, InputStreamReader}
import java.security.cert.{CertificateFactory, X509Certificate}
import java.security.{KeyStore, SecureRandom, Security}
import java.util.Base64

import com.goyeau.kubernetes.client.KubeConfig
import javax.net.ssl.{KeyManagerFactory, SSLContext, TrustManagerFactory}
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter
import org.bouncycastle.openssl.{PEMKeyPair, PEMParser}

object SslContexts {
  private val TrustStoreSystemProperty         = "javax.net.ssl.trustStore"
  private val TrustStorePasswordSystemProperty = "javax.net.ssl.trustStorePassword"
  private val KeyStoreSystemProperty           = "javax.net.ssl.keyStore"
  private val KeyStorePasswordSystemProperty   = "javax.net.ssl.keyStorePassword"

  def fromConfig(config: KubeConfig): SSLContext = {
    val sslContext = SSLContext.getInstance("TLS")
    sslContext.init(keyManagers(config), trustManagers(config), new SecureRandom)
    sslContext
  }

  private def keyManagers(config: KubeConfig) = {
    // Client certificate
    val certDataStream = config.clientCertData.map(data => new ByteArrayInputStream(Base64.getDecoder.decode(data)))
    val certFileStream = config.clientCertFile.map(new FileInputStream(_))

    // Client key
    val keyDataStream = config.clientKeyData.map(data => new ByteArrayInputStream(Base64.getDecoder.decode(data)))
    val keyFileStream = config.clientKeyFile.map(new FileInputStream(_))

    for {
      keyStream  <- keyDataStream.orElse(keyFileStream)
      certStream <- certDataStream.orElse(certFileStream)
    } yield {
      Security.addProvider(new BouncyCastleProvider())
      val pemKeyPair =
        new PEMParser(new InputStreamReader(keyStream)).readObject().asInstanceOf[PEMKeyPair] // scalafix:ok
      val privateKey = new JcaPEMKeyConverter().setProvider("BC").getPrivateKey(pemKeyPair.getPrivateKeyInfo)

      val certificateFactory = CertificateFactory.getInstance("X509")
      val certificate        = certificateFactory.generateCertificate(certStream).asInstanceOf[X509Certificate] // scalafix:ok

      defaultKeyStore.setKeyEntry(
        certificate.getSubjectX500Principal.getName,
        privateKey,
        config.clientKeyPass.fold(Array.empty[Char])(_.toCharArray),
        Array(certificate)
      )
    }

    val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
    keyManagerFactory.init(defaultKeyStore, Array.empty)
    keyManagerFactory.getKeyManagers
  }

  private lazy val defaultKeyStore = {
    val propertyKeyStoreFile =
      Option(System.getProperty(KeyStoreSystemProperty, "")).filter(_.nonEmpty).map(new File(_))

    val keyStore = KeyStore.getInstance(KeyStore.getDefaultType)
    keyStore.load(
      propertyKeyStoreFile.map(new FileInputStream(_)).orNull,
      System.getProperty(KeyStorePasswordSystemProperty, "").toCharArray
    )
    keyStore
  }

  private def trustManagers(config: KubeConfig) = {
    val certDataStream = config.caCertData.map(data => new ByteArrayInputStream(Base64.getDecoder.decode(data)))
    val certFileStream = config.caCertFile.map(new FileInputStream(_))

    certDataStream.orElse(certFileStream).foreach { certStream =>
      val certificateFactory = CertificateFactory.getInstance("X509")
      val certificate        = certificateFactory.generateCertificate(certStream).asInstanceOf[X509Certificate] // scalafix:ok
      defaultTrustStore.setCertificateEntry(certificate.getSubjectX500Principal.getName, certificate)
    }

    val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
    trustManagerFactory.init(defaultTrustStore)
    trustManagerFactory.getTrustManagers
  }

  private lazy val defaultTrustStore = {
    val securityDirectory = s"${System.getProperty("java.home")}/lib/security"

    val propertyTrustStoreFile =
      Option(System.getProperty(TrustStoreSystemProperty, "")).filter(_.nonEmpty).map(new File(_))
    val jssecacertsFile = Option(new File(s"$securityDirectory/jssecacerts")).filter(f => f.exists && f.isFile)
    val cacertsFile     = new File(s"$securityDirectory/cacerts")

    val keyStore = KeyStore.getInstance(KeyStore.getDefaultType)
    keyStore.load(
      new FileInputStream(propertyTrustStoreFile.orElse(jssecacertsFile).getOrElse(cacertsFile)),
      System.getProperty(TrustStorePasswordSystemProperty, "changeit").toCharArray
    )
    keyStore
  }
} 
Example 7
Source File: InfinispanClient.scala    From infinispan-spark   with Apache License 2.0 5 votes vote down vote up
package org.infinispan.spark.test

import java.net.HttpURLConnection
import java.security.SecureRandom
import java.security.cert.X509Certificate

import javax.net.ssl._
import sttp.client.{HttpURLConnectionBackend, basicRequest, _}


case class InfinispanClient(port: Int = 11222, tls: Boolean) {
   val SkipSSLValidation: HttpURLConnection => Unit = {
      case connection: HttpsURLConnection =>
         val sc = SSLContext.getInstance("TLS")
         sc.init(null, Array(new TrustAllX509TrustManager), new SecureRandom)
         connection.setSSLSocketFactory(sc.getSocketFactory)
         connection.setHostnameVerifier(new HostnameVerifier {
            override def verify(s: String, sslSession: SSLSession) = true
         })
      case _ =>
   }

   implicit val backend = HttpURLConnectionBackend(customizeConnection = SkipSSLValidation)

   val protocol = if (tls) "https" else "http"

   val baseURL = s"$protocol://localhost:$port/rest/v2"

   def shutdownServer(): Unit = {
      shutDownResource("server")
   }

   def shutdownCluster(): Unit = {
      shutDownResource("cluster")
   }

   private def shutDownResource(resource: String): Unit = {
      val request = basicRequest.get(uri"$baseURL/$resource?action=stop")
      val response = request.send()
      val code = response.code.code
      if (code < 200 || code > 204) throw new Exception(s"Failed to stop $resource, code $code")
   }

   def cacheExists(name: String): Boolean = {
      val request = basicRequest.get(uri"$baseURL/caches/")
      val response = request.send()
      response.body match {
         case Right(x) => ujson.read(x).arr.map(_.str).contains(name)
         case _ => false
      }
   }

   def isHealthy(cacheManager: String, members: Int): Boolean = {
      val request = basicRequest.get(uri"$baseURL/cache-managers/$cacheManager/health/")
      val response = request.send()
      response.body match {
         case Right(x) =>
            val json = ujson.read(x)
            val clusterHealth = json("cluster_health")
            val health = clusterHealth("health_status")
            val nodes = clusterHealth("number_of_nodes")
            health.str == "HEALTHY" && nodes.num == members
         case Left(x) => throw new RuntimeException(x)
      }
   }

   def createCache(cacheName: String, cfg: String) = {
      if (!cacheExists(cacheName)) {
         val response = basicRequest.post(uri"$baseURL/caches/$cacheName")
           .contentType("application/json")
           .body(cfg).send()
         val status = response.code.code
         if (status < 200 || status > 204) throw new RuntimeException(s"Failed to create cache, code $status")
      }
   }

   class TrustAllX509TrustManager extends X509TrustManager {
      def getAcceptedIssuers = new Array[X509Certificate](0)

      def checkClientTrusted(certs: Array[X509Certificate], authType: String): Unit = {}

      def checkServerTrusted(certs: Array[X509Certificate], authType: String): Unit = {}
   }

} 
Example 8
Source File: ProxyCrawler.scala    From ProxyCrawler   with Apache License 2.0 5 votes vote down vote up
package org.crowdcrawler.proxycrawler

import java.io.IOException
import java.net.URI
import java.security.cert.X509Certificate

import com.typesafe.scalalogging.Logger
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClients
import org.apache.http.ssl.{TrustStrategy, SSLContexts}
import org.apache.http.conn.ssl.{NoopHostnameVerifier, SSLConnectionSocketFactory}
import org.apache.http.util.EntityUtils
import org.crowdcrawler.proxycrawler.crawler.plugins.AbstractPlugin

import org.apache.http.HttpHeaders
import org.slf4j.LoggerFactory

import scala.collection.immutable
import scala.collection.mutable


class ProxyCrawler(plugins: List[AbstractPlugin]) {
  *;q=0.8"),
    (HttpHeaders.ACCEPT_ENCODING, "gzip, deflate, sdch"),
    (HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4"),
    (HttpHeaders.CONNECTION, "keep-alive")
  )

  private val CLIENT = {
    // trust all certificates including self-signed certificates
    val sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
      def isTrusted(chain: Array[X509Certificate], authType: String) = true
    }).build()
    val connectionFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)
    HttpClients.custom().setSSLSocketFactory(connectionFactory).build()
  }

  def apply(classNames: String*): ProxyCrawler = {
    val plugins = mutable.ListBuffer.empty[AbstractPlugin]
    for (className <- classNames) {
      val clazz = Class.forName("org.crowdcrawler.proxycrawler.crawler.plugins." + className)
      plugins += clazz.newInstance().asInstanceOf[AbstractPlugin]
    }
    new ProxyCrawler(plugins.toList)
  }

  private def createRequest(uri: URI, headers: immutable.Map[String, String]): HttpGet = {
    val request = new HttpGet(uri)
    for (header <- headers) {
      request.setHeader(header._1, header._2)
    }
    request
  }
} 
Example 9
Source File: HttpsProxyChecker.scala    From ProxyCrawler   with Apache License 2.0 5 votes vote down vote up
package org.crowdcrawler.proxycrawler.checker

import java.net.URI
import java.nio.charset.StandardCharsets
import java.security.cert.X509Certificate

import org.apache.http.HttpHost
import org.apache.http.annotation.ThreadSafe
import org.apache.http.client.methods.HttpGet
import org.apache.http.conn.ssl.{NoopHostnameVerifier, SSLConnectionSocketFactory}
import org.apache.http.impl.client.HttpClients
import org.apache.http.ssl.{TrustStrategy, SSLContexts}
import org.apache.http.util.EntityUtils


@ThreadSafe
private[checker] object HttpsProxyChecker extends AbstractProxyChecker {
  // trust all certificates including self-signed certificates
  private[checker] val SSL_CONTEXT = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
    def isTrusted(chain: Array[X509Certificate], authType: String) = true
  }).build()
  private val CLIENT = {
    val connectionFactory = new SSLConnectionSocketFactory(SSL_CONTEXT, NoopHostnameVerifier.INSTANCE)
    HttpClients.custom().setSSLSocketFactory(connectionFactory).setMaxConnTotal(AbstractProxyChecker.MAX_CONN)
      .disableRedirectHandling().build()
  }
  private val TARGET_URL = new URI("https://www.google.com")


  def check(host: String, port: Int): (Int, Int) = {
    val request = new HttpGet(TARGET_URL)
    AbstractProxyChecker.configureRequest(request, Some(new HttpHost(host, port, "http")))

    val response = CLIENT.execute(request)

    val statusCode = response.getStatusLine.getStatusCode
    val html = EntityUtils.toString(response.getEntity, StandardCharsets.UTF_8)
    if (statusCode == 200 && html.contains("<title>Google</title>")) (statusCode, html.getBytes.length)
    else (statusCode, -1)
  }
} 
Example 10
Source File: TLS.scala    From skuber   with Apache License 2.0 5 votes vote down vote up
package skuber.api.security

import java.net.Socket
import javax.net.ssl._
import java.security.cert.X509Certificate
import java.security.SecureRandom

import skuber.api.client.{AuthInfo, CertAuth, Context, PathOrData}


object TLS {
  
  // This trust manager supports the InsecureSkipTLSVerify flag in kubeconfig files -
  // it always trusts the server i.e. skips verifying the server cert for a TLS connection
  object InsecureSkipTLSVerifyTrustManager extends X509ExtendedTrustManager
  {
    def getAcceptedIssuers = Array.empty[X509Certificate]
    def checkClientTrusted(certs: Array[X509Certificate], authType: String) : Unit = {}
    def checkServerTrusted(certs: Array[X509Certificate], authType: String) : Unit = {}
    def checkClientTrusted(certs: Array[X509Certificate], s: String, socket: Socket): Unit = {}
    def checkClientTrusted(certs: Array[X509Certificate], s: String, sslEngine: SSLEngine): Unit = {}
    def checkServerTrusted(certs: Array[X509Certificate], s: String, socket: Socket): Unit = {}
    def checkServerTrusted(certs: Array[X509Certificate], s: String, sslEngine: SSLEngine): Unit = {}
  }
   
  val skipTLSTrustManagers = Array[TrustManager](InsecureSkipTLSVerifyTrustManager)
 
  val HttpsPattern = "https:.*".r
  val HttpPattern = "http:.*".r
  
  def establishSSLContext(k8sContext: Context): Option[SSLContext] = {
    k8sContext.cluster.server match {
      case HttpPattern(_*) => None // not using SSL so return no context
      case HttpsPattern(_*) => Some(buildSSLContext(k8sContext))
      case _ => throw new Exception("Kubernetes cluster API server URL does not begin with either http or https : "
                                    + k8sContext.cluster.server)
    }
  }
  
   private def buildSSLContext(k8sContext: Context): SSLContext = {
     val sslContext = SSLContext.getInstance("TLS")
     
     val skipTLSVerify = k8sContext.cluster.insecureSkipTLSVerify
     val clusterCertConfig = k8sContext.cluster.certificateAuthority
     val trustManagers = getTrustManagers(skipTLSVerify,clusterCertConfig) 

     val keyManagers = getKeyManagers(k8sContext.authInfo)
     
     sslContext.init(keyManagers.orNull, trustManagers.orNull, new SecureRandom())
     sslContext
   }
   
   private def getTrustManagers(skipTLSVerify: Boolean, serverCertConfig: Option[PathOrData]) : Option[Array[TrustManager]] =
     if (skipTLSVerify) 
       Some(skipTLSTrustManagers)
     else
       serverCertConfig map { certPathOrData =>
           val clusterServerCerts = SecurityHelper.getCertificates(certPathOrData)
           val trustStore = SecurityHelper.createTrustStore(clusterServerCerts)
           val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
           tmf.init(trustStore)
           tmf.getTrustManagers
       }
  
   private def getKeyManagers(authInfo: AuthInfo) : Option[Array[KeyManager]] =
     authInfo match {
       case CertAuth(clientCert, clientKey, userName) =>
         val certs = SecurityHelper.getCertificates(clientCert)
         val key = SecurityHelper.getPrivateKey(clientKey)
         val keyStore = SecurityHelper.createKeyStore(userName.getOrElse("skuber"), certs, key)
         val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
         kmf.init(keyStore, "changeit".toCharArray)
         Some(kmf.getKeyManagers)
       case _ => None
     }
       
} 
Example 11
Source File: DisableSSLCertificateCheckUtil.scala    From BacklogMigration-Redmine   with MIT License 5 votes vote down vote up
package com.nulabinc.backlog.r2b.utils

import java.security.cert.X509Certificate
import javax.net.ssl._

import com.nulabinc.backlog.migration.common.utils.Logging


object DisableSSLCertificateCheckUtil extends Logging {

  def disableChecks(): Unit = {
    try {
      val context: SSLContext = SSLContext.getInstance("TLS")
      val trustManagerArray: Array[TrustManager] = Array(
        new NullX509TrustManager()
      )
      context.init(null, trustManagerArray, null)
      HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory)
      HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier())
    } catch {
      case e: Exception =>
        logger.error(e.getMessage, e)
    }
  }

  private[this] class NullX509TrustManager extends X509TrustManager {

    override def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = ()

    override def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = ()

    override def getAcceptedIssuers: Array[X509Certificate] =
      Array.ofDim[X509Certificate](0)
  }

  private[this] class NullHostnameVerifier extends HostnameVerifier {

    override def verify(hostname: String, session: SSLSession): Boolean = true
  }

}