Skip to content
Permalink
Browse files

common config chnages for selsigned certificate

  • Loading branch information...
shaileshp0110 committed Jun 12, 2019
1 parent 547f824 commit da426afec19c1234b39c8e5f560c9a009168a4dd
@@ -1,8 +1,9 @@
package io.iohk.scalanet.peergroup

import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.security.PrivateKey
import java.security.cert.X509Certificate
import java.security.cert.{Certificate, X509Certificate}

import io.iohk.decco.BufferInstantiator.global.HeapByteBuffer
import io.iohk.decco._
@@ -22,6 +23,7 @@ import monix.eval.Task
import monix.reactive.Observable
import monix.reactive.subjects.{PublishSubject, ReplaySubject, Subject}
import org.slf4j.LoggerFactory

import scala.concurrent.Promise
import scala.util.Success
import scala.collection.JavaConverters._
@@ -37,7 +39,7 @@ import scala.collection.JavaConverters._
* @param codec a decco codec for reading writing messages to NIO ByteBuffer.
* @tparam M the message type.
*/
class TLSPeerGroup[M](val config: Config)(implicit codec: Codec[M]) extends TerminalPeerGroup[InetMultiAddress, M]() {
class TLSPeerGroup[M](val config: Config)(implicit codec: Codec[M],bufferInstantiator: BufferInstantiator[ByteBuffer]) extends TerminalPeerGroup[InetMultiAddress, M]() {

private val log = LoggerFactory.getLogger(getClass)

@@ -49,7 +51,7 @@ class TLSPeerGroup[M](val config: Config)(implicit codec: Codec[M]) extends Term
private val messageSubject = ReplaySubject[M]()

private val sslServerCtx = SslContextBuilder
.forServer(config.certChainPrivateKey, config.certChain: _*)
.forServer(config.certChainPrivateKey, config.certChain.asInstanceOf[List[X509Certificate]]: _*)
.ciphers(TLSPeerGroup.supportedCipherSuites.asJava)
.build()

@@ -101,7 +103,7 @@ class TLSPeerGroup[M](val config: Config)(implicit codec: Codec[M]) extends Term

private val sslClientCtx = SslContextBuilder
.forClient()
.trustManager(config.trustStore: _*)
.trustManager(config.trustStore.asInstanceOf[List[X509Certificate]]: _*)
.build()

private val bootstrap: Bootstrap = clientBootstrap
@@ -225,17 +227,17 @@ object TLSPeerGroup {
bindAddress: InetSocketAddress,
processAddress: InetMultiAddress,
certChainPrivateKey: PrivateKey,
certChain: List[X509Certificate],
trustStore: List[X509Certificate],
certChain: List[Certificate],
trustStore: List[Certificate],
clientAuthRequired: Boolean
)

object Config {
def apply(
bindAddress: InetSocketAddress,
certChainPrivateKey: PrivateKey,
certChain: List[X509Certificate],
trustStore: List[X509Certificate]
certChain: List[Certificate],
trustStore: List[Certificate]
): Config =
Config(
bindAddress,
@@ -249,8 +251,8 @@ object TLSPeerGroup {
def apply(
bindAddress: InetSocketAddress,
certChainPrivateKey: PrivateKey,
certChain: List[X509Certificate],
trustStore: List[X509Certificate],
certChain: List[Certificate],
trustStore: List[Certificate],
clientAuthRequired: Boolean = true
): Config =
Config(bindAddress, InetMultiAddress(bindAddress), certChainPrivateKey, certChain, trustStore, clientAuthRequired)
@@ -115,7 +115,7 @@ object NetUtils {
Await.result(pg.initialize().runAsync, 10 seconds)
pg
}
def randomTLSPeerGroup[M](implicit scheduler: Scheduler, codec: Codec[M]): TLSPeerGroup[M] = {
def randomTLSPeerGroup[M](implicit scheduler: Scheduler, codec: Codec[M],bufferInstantiator: BufferInstantiator[ByteBuffer]): TLSPeerGroup[M] = {
val sc1 = new SelfSignedCertificate()
val pg = new TLSPeerGroup(TLSPeerGroup.Config(aRandomAddress(), sc1.key(), List(sc1.cert()), Nil))
Await.result(pg.initialize().runAsync, 10 seconds)
@@ -146,8 +146,8 @@ object NetUtils {

def withTwoRandomTLSPeerGroups[M](clientAuth: Boolean = false)(
testCode: (TLSPeerGroup[M], TLSPeerGroup[M]) => Any
)(implicit scheduler: Scheduler, codec: Codec[M]): Unit = {
val (pg1, pg2) = random2TLSPPeerGroup(clientAuth)(scheduler, codec)
)(implicit scheduler: Scheduler, codec: Codec[M],bufferInstantiator: BufferInstantiator[ByteBuffer]): Unit = {
val (pg1, pg2) = random2TLSPPeerGroup(clientAuth)(scheduler, codec,bufferInstantiator)
try {
testCode(pg1, pg2)
} finally {
@@ -158,7 +158,7 @@ object NetUtils {

def random2TLSPPeerGroup[M](
clientAuth: Boolean
)(implicit scheduler: Scheduler, codec: Codec[M]): (TLSPeerGroup[M], TLSPeerGroup[M]) = {
)(implicit scheduler: Scheduler, codec: Codec[M],bufferInstantiator: BufferInstantiator[ByteBuffer]): (TLSPeerGroup[M], TLSPeerGroup[M]) = {
val address1 = aRandomAddress()
val address2 = aRandomAddress()
val sc1 = new SelfSignedCertificate()
@@ -107,6 +107,8 @@ object DTLSPeerGroupSpec {
}
}



def dtlsPeerGroup[M](
config: Config
)(implicit codec: Codec[M], bufferInstantiator: BufferInstantiator[ByteBuffer]): DTLSPeerGroup[M] = {
@@ -1,18 +1,27 @@
package io.iohk.scalanet.peergroup

import java.nio.ByteBuffer
import java.security.{KeyStore, PrivateKey}
import java.security.cert.{Certificate, CertificateFactory}

import io.iohk.decco.auto._
import io.iohk.scalanet.NetUtils
import io.iohk.scalanet.NetUtils._
import io.iohk.scalanet.TaskValues._
import monix.execution.Scheduler.Implicits.global
import org.scalatest.Matchers._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.concurrent.ScalaFutures._
import org.scalatest.{BeforeAndAfterAll, FlatSpec}
import io.iohk.scalanet.peergroup.TLSPeerGroup._
import io.iohk.decco.BufferInstantiator.global.HeapByteBuffer
import io.iohk.decco.{BufferInstantiator, Codec}

import scala.concurrent.Future
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.util.Random

import TLSPeerGroupSpec._
import io.netty.handler.ssl.util.SelfSignedCertificate
class TLSPeerGroupSpec extends FlatSpec with BeforeAndAfterAll {

implicit val patienceConfig: ScalaFutures.PatienceConfig = PatienceConfig(5 seconds)
@@ -41,6 +50,23 @@ class TLSPeerGroupSpec extends FlatSpec with BeforeAndAfterAll {

}

it should "send and receive a message" in {
withTwoTLSPeerGroups[String](selfSignedCertConfig, selfSignedCertConfig) { (alice, bob) =>
val alicesMessage = Random.alphanumeric.take(1024 * 4).mkString
val bobsMessage = Random.alphanumeric.take(1024 * 4).mkString

val bobReceived: Future[String] = bob.server().mergeMap(channel => channel.in).headL.runAsync
bob.server().foreach(channel => channel.sendMessage(bobsMessage).runAsync)

val aliceClient = alice.client(bob.processAddress).evaluated
val aliceReceived = aliceClient.in.headL.runAsync
aliceClient.sendMessage(alicesMessage).runAsync

bobReceived.futureValue shouldBe alicesMessage
aliceReceived.futureValue shouldBe bobsMessage
}
}

it should "shutdown a TLSPeerGroup properly" in {
val tlsPeerGroup = randomTLSPeerGroup[String]
isListening(tlsPeerGroup.config.bindAddress) shouldBe true
@@ -61,4 +87,75 @@ class TLSPeerGroupSpec extends FlatSpec with BeforeAndAfterAll {
firstInbound.futureValue.to shouldBe alice.processAddress
secondInbound.futureValue.to shouldBe alice.processAddress
}


}

object TLSPeerGroupSpec{

def signedCertConfig(alias: String): Config = {
import scala.collection.JavaConverters._
val fact = CertificateFactory.getInstance("X.509")
val certChain = fact
.generateCertificates(DTLSPeerGroupSpec.getClass.getClassLoader.getResourceAsStream(s"${alias}.pem"))
.asScala
.toList

Config(aRandomAddress(),keyAt(alias),certChain, NetUtils.trustedCerts.toList)
}

def selfSignedCertConfig(alias: String): Config = {

val key = keyStore.getKey(alias,"password".toCharArray).asInstanceOf[PrivateKey]
val certChain = keyStore.getCertificateChain(alias).toList
val trustStore = List(keyStore.getCertificate("bob"))
Config(aRandomAddress(),key ,certChain, trustStore)

}


def withTwoTLSPeerGroups[M](cgens: (String => Config)*)(
testCode: (TLSPeerGroup[M], TLSPeerGroup[M]) => Any
)(implicit codec: Codec[M], bufferInstantiator: BufferInstantiator[ByteBuffer]): Unit = cgens.foreach { cgen =>
val pg1 = tlsPeerGroup[M](cgen("alice"))
val pg2 = tlsPeerGroup[M](cgen("bob"))
println(s"Alice is ${pg1.processAddress}")
println(s"Bob is ${pg2.processAddress}")
try {
testCode(pg1, pg2)
} finally {
pg1.shutdown()
pg2.shutdown()
}
}

def tlsPeerGroup[M](config: Config)(implicit codec: Codec[M], bufferInstantiator: BufferInstantiator[ByteBuffer]): TLSPeerGroup[M] = {
val pg = new TLSPeerGroup[M](config)
Await.result(pg.initialize().runAsync, Duration.Inf)
pg
}

val keyStore = {
val keyStore = KeyStore.getInstance("JKS")
keyStore.load(null)
val aliceSc = new SelfSignedCertificate()
val bobSc = new SelfSignedCertificate()

keyStore.setCertificateEntry("alice", bobSc.cert())
keyStore.setKeyEntry("alice",aliceSc.key(),"password".toCharArray,Array(aliceSc.cert()))

keyStore.setCertificateEntry("bob", aliceSc.cert())
keyStore.setKeyEntry("bob",bobSc.key(),"password".toCharArray,Array(bobSc.cert()))

keyStore
}


def keyAt(alias: String): PrivateKey = {
NetUtils.keyStore.getKey(alias, "password".toCharArray).asInstanceOf[PrivateKey]
}

def certAt(alias: String): Certificate = {
NetUtils.keyStore.getCertificate(alias)
}
}

0 comments on commit da426af

Please sign in to comment.
You can’t perform that action at this time.