升级转到TLS连接(Upgrade a connection to TLS in Go)

2019-07-02 19:59发布

我有一个像这样一个开放的TCP连接,并读取它的循环

for {
  // tx.Text is of type textproto.Conn
  // the underlying connection is stored in tx.Conn
  l, err := tx.Text.Reader.ReadLine()

  // do stuff with the text line ...
}

现在,我想升级这样的连接,TLS( TlsConf包含加载证书tls.LoadX509KeyPair

tx.Conn = tls.Server(tx.Conn, tx.Server.Conf.TlsConf)
tx.Text = textproto.NewConn(tx.Conn)

当我做到这一点我在客户端上分段故障时,服务器会试图进行握手。 我执行一个SMTP服务器,并正与测试它swaks使用-tls标志。 的终端输出swaks是以下

-> STARTTLS
<-  220 Start TLS
Segmentation fault: 11

由于swaks是一个测试工具,并与SMTP的NodeJS实现我以前工作过,我不怀疑的错误是在客户端。

我做了什么错误或缺什么?

PS:当TLS连接从现有不安全的连接开始,这是什么究竟怎样呢? 客户是否建立了不同的端口上一个新的连接或连接重用?

Answer 1:

下面是如何将net.conn升级到tls.con:

1)某处在你的代码,你有这些变量定义

var TLSconfig *tls.Config
...
// conn is a normal connection of type net.Conn
conn, err := listener.Accept()
...

2)以上的某处初始化TLSConfig,做这样的事情

cert, err := tls.LoadX509KeyPair("/path/to/cert", "/path/to/key")
if err != nil {
    // ...
}
TLSconfig = &tls.Config{
Certificates: []tls.Certificate{cert}, 
ClientAuth: tls.VerifyClientCertIfGiven, 
ServerName: "example.com"}

3)此时你正在读/写为标准连接。

当客户端发出STARTTLS命令,在您的服务器做到这一点:

// Init a new TLS connection. I need a *tls.Conn type 
// so that I can do the Handshake()
var tlsConn *tls.Conn
tlsConn = tls.Server(client.socket, TLSconfig)
// run a handshake
tlsConn.Handshake()
// Here is the trick. Since I do not need to access 
// any of the TLS functions anymore,
// I can convert tlsConn back in to a net.Conn type
conn = net.Conn(tlsConn)

接下来,你可以大概与新的连接等更新缓冲区

测试你的服务器是这样的:

openssl s_client -starttls smtp -crlf -connect  example.com:25

这允许您通过TLS连接服务器进行交互,并可以发出一些指令等

更多关于围棋的转换

我想转换是另一个原因,是什么让走这么强大!

http://golang.org/ref/spec#Conversions

http://golang.org/doc/effective_go.html#conversions



Answer 2:

抛弃swaks,内置了一款小工具来测试TLS使用转到自己的smtp.SendMail:

package main

import (
  "fmt"
  "net/smtp"
)

func main() {
  err := smtp.SendMail(
    "127.0.0.1:2525",
    nil,
    "src@test.local",
    []string{"dst@test.local"},
    []byte("Hello! Just testing."),
  )
  if err != nil {
    panic(err)
  }
}


文章来源: Upgrade a connection to TLS in Go
标签: go ssl