如何使用Akka在Scala中使用TLS打开TCP连接 [英] How to open TCP connection with TLS in scala using akka

查看:150
本文介绍了如何使用Akka在Scala中使用TLS打开TCP连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个Scala客户端,该客户端通过带有TLS的tcp连接来讨论专有协议。

I want to write a Scala client that talks a proprietary protocol over a tcp connection with TLS.

基本上,我想从Scala中的Node.js重写以下代码:

Basically, I want to rewrite the following code from Node.js in Scala:

var conn_options = {
        host: endpoint,
        port: port
};
tlsSocket = tls.connect(conn_options, function() {
      if (tlsSocket.authorized) {
        logger.info('Successfully established a connection');

        // Now that the connection has been established, let's perform the handshake
        // Identification frame:
        // 1 | I | id_size | id
        var idFrameTypeAndVersion = "1I";
        var clientIdString = "foorbar";
        var idDataBuffer = new Buffer(idFrameTypeAndVersion.length + 1 + clientIdString.length);

        idDataBuffer.write(idFrameTypeAndVersion, 0 , 
        idFrameTypeAndVersion.length);

        idDataBuffer.writeUIntBE(clientIdString.length, 
        idFrameTypeAndVersion.length, 1);
        idDataBuffer.write(clientIdString, idFrameTypeAndVersion.length + 1, clientIdString.length);

        // Send the identification frame to Logmet
        tlsSocket.write(idDataBuffer);

      }
      ...
}

来自 akka文档我在纯tcp上找到了Akka的一个很好的例子,但是我不知道如何使用TLS来增强该例子套接字连接。文档的某些较旧版本显示了 with ssl / tls ,但是在较新的版本中却没有。

From the akka documentation I found a good example with Akka over plain tcp, but I've no clue how to enhance the example using a TLS socket connection. There are some older versions of the documentation that shows an example with ssl/tls but that's missed in the newer version.

我找到了有关 TLS 对象在Akka中,但是我没有找到很好的例子。

I've found documentation about a TLS object in Akka but I did not found any good example around it.

在此先感谢!!

推荐答案

使用以下代码并希望共享。

Got it working with the following code and want to share.

基本上,我开始查看 TcpTlsEcho.java

我遵循了 akka-streams 。可以在以下博客帖子

I followed the documentation of akka-streams. Another very good example that shows and illustrate the usage of akka-streams can be found in the following blog post

连接设置和流程如下:

    /**
    +---------------------------+               +---------------------------+
    | Flow                      |               | tlsConnectionFlow         |
    |                           |               |                           |
    | +------+        +------+  |               |  +------+        +------+ |
    | | SRC  | ~Out~> |      | ~~> O2   --  I1 ~~> |      |  ~O1~> |      | |
    | |      |        | LOGG |  |               |  | TLS  |        | CONN | |
    | | SINK | <~In~  |      | <~~ I2   --  O2 <~~ |      | <~I2~  |      | |
    | +------+        +------+  |               |  +------+        +------+ |
    +---------------------------+               +---------------------------+
**/
// the tcp connection to the server
val connection = Tcp().outgoingConnection(address, port)

// ignore the received data for now. There are different actions to implement the Sink.
val sink = Sink.ignore

// create a source as an actor reference
val source = Source.actorRef(1000, OverflowStrategy.fail)

// join the TLS BidiFlow (see below) with the connection
val tlsConnectionFlow = tlsStage(TLSRole.client).join(connection)

// run the source with the TLS conection flow that is joined with a logging step that prints the bytes that are sent and or received from the connection.
val sourceActor = tlsConnectionFlow.join(logging).to(sink).runWith(source) 

// send a message to the sourceActor that will be send to the Source of the stream
sourceActor ! ByteString("<message>")

TLS连接流是BidiFlow。我的第一个简单示例将忽略所有证书,并避免管理信任和密钥存储。可以在上面的.java示例中找到执行该操作的示例。

The TLS connection flow is a BidiFlow. My first simple example ignores all certificates and avoids managing trust and key stores. Examples how that is done can be found in the .java example above.

  def tlsStage(role: TLSRole)(implicit system: ActorSystem) = {
    val sslConfig = AkkaSSLConfig.get(system)
    val config = sslConfig.config

    // create a ssl-context that ignores self-signed certificates
    implicit val sslContext: SSLContext = {
        object WideOpenX509TrustManager extends X509TrustManager {
            override def checkClientTrusted(chain: Array[X509Certificate], authType: String) = ()
            override def checkServerTrusted(chain: Array[X509Certificate], authType: String) = ()
            override def getAcceptedIssuers = Array[X509Certificate]()
        }

        val context = SSLContext.getInstance("TLS")
        context.init(Array[KeyManager](), Array(WideOpenX509TrustManager), null)
        context
    }
    // protocols
    val defaultParams = sslContext.getDefaultSSLParameters()
    val defaultProtocols = defaultParams.getProtocols()
    val protocols = sslConfig.configureProtocols(defaultProtocols, config)
    defaultParams.setProtocols(protocols)

    // ciphers
    val defaultCiphers = defaultParams.getCipherSuites()
    val cipherSuites = sslConfig.configureCipherSuites(defaultCiphers, config)
    defaultParams.setCipherSuites(cipherSuites)

    val firstSession = new TLSProtocol.NegotiateNewSession(None, None, None, None)
       .withCipherSuites(cipherSuites: _*)
       .withProtocols(protocols: _*)
       .withParameters(defaultParams)

    val clientAuth = getClientAuth(config.sslParametersConfig.clientAuth)
    clientAuth map { firstSession.withClientAuth(_) }

    val tls = TLS.apply(sslContext, firstSession, role)

    val pf: PartialFunction[TLSProtocol.SslTlsInbound, ByteString] = {
      case TLSProtocol.SessionBytes(_, sb) => ByteString.fromByteBuffer(sb.asByteBuffer)
    }

    val tlsSupport = BidiFlow.fromFlows(
        Flow[ByteString].map(TLSProtocol.SendBytes),
        Flow[TLSProtocol.SslTlsInbound].collect(pf));

    tlsSupport.atop(tls);
  }

  def getClientAuth(auth: ClientAuth) = {
     if (auth.equals(ClientAuth.want)) {
         Some(TLSClientAuth.want)
     } else if (auth.equals(ClientAuth.need)) {
         Some(TLSClientAuth.need)
     } else if (auth.equals(ClientAuth.none)) {
         Some(TLSClientAuth.none)
     } else {
         None
     }
  }

为了完成该操作,还有一个日志记录阶段已被实现为BidiFlow。

And for completion there is the logging stage that has been implemented as a BidiFlow as well.

  def logging: BidiFlow[ByteString, ByteString, ByteString, ByteString, NotUsed] = {
    // function that takes a string, prints it with some fixed prefix in front and returns the string again
    def logger(prefix: String) = (chunk: ByteString) => {
      println(prefix + chunk.utf8String)
      chunk
    }

    val inputLogger = logger("> ")
    val outputLogger = logger("< ")

    // create BidiFlow with a separate logger function for each of both streams
    BidiFlow.fromFunctions(outputLogger, inputLogger)
 }

我将进一步尝试改善和更新答案。希望能有所帮助。

I will further try to improve and update the answer. Hope that helps.

这篇关于如何使用Akka在Scala中使用TLS打开TCP连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆