gpt4 book ai didi

go - 在 Go 中升级到 TLS 的连接

转载 作者:IT王子 更新时间:2023-10-29 01:11:49 26 4
gpt4 key购买 nike

我有一个打开的 TCP 连接并使用 for 循环读取它

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 是一个经过测试的工具,并且与我之前使用的 nodeJS SMTP 实现一起工作,所以我不怀疑错误出在客户端。

我做错了什么或遗漏了什么?

PS:当从现有的不安全连接启动 TLS 连接时,究竟会发生什么?客户端是在不同端口上建立新连接还是重用连接?

最佳答案

以下是将 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 连接与服务器进行交互,您可以发出一些命令等。

详细了解 Go 中的转化

我想转换是让 Go 如此强大的另一个原因!

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

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

关于go - 在 Go 中升级到 TLS 的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13110713/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com