drsxobip501258 2014-04-15 19:26
浏览 13
已采纳

通过tls.Server连接进行读写

I'm writing an SMTP server in Go. Implementing the STARTTLS command requires usage of the crypto/tls package. Here seems like I should be able to "convert" the net.Conn object to a tls.Conn one, and then I'd be able to seamlessly read and write using the encryption TLS provides.

However, even if I'm able to do the first part of the above, when I try to read or write to the TLS-protected connection, the Read() and Write() functions called are not the ones of the tls.Conn object, but of the underlying net.Conn one.

What I'm currently doing looks like this:

type Handler struct {
    Conn net.Conn
}
//...
client := Handler{Conn: /*socket*/}
client.Conn.Write([]byte("Hello!")) //regular write
//the STARTTLS command has been received, switch to tls.Conn and handshake
client.Conn = tls.Server(client.Conn, &TlsConfig) //client.Conn should be now of type tls.Conn
//either casting or not give me the same results
client.Conn.Handshake() //not necessary, it is called on the first Read() or Write() by default
//...
client.Conn.Write([]byte("Hello again!")) //writes clear, unencrypted text
//...
rdr := bufio.NewReader(client.Conn) //might this be the culprit? I don't think it is, since it should just wrap the regular functions
line, err := rdr.ReadString/*or Line*/('
')
//...
//line = something like À"À!27ÀÀ9ÀÀÀÀ and other client-encrypted text

I've seen that numerous people, including the standard net/smtp package, use the text/proto package to parse client commands. However, I want to use my own (and also want to sort this out). As in the comment earlier, I don't think the culprit lies here, since it should just wrap functions, shouldn't it?

Might it be the client.Conn = tls.Server(client.Conn, &TlsConfig) object switch?

The SSL key and certificate I'm using are selfsigned, generated with OpenSSL. To test, I'm using the two methods suggested in the StackOverflow question linked above: openssl s_client -starttls smtp -crlf [-tls1] -connect localhost:25 and a simple net/smtp.SendMail() call. I'm compiling against Go 1.2.1 (linux/amd64).

I've also tried sniffing with Wireshark, and indeed it led me to know what I said above. Also, calling Handshake() doesn't apparently actually handshake.

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • dongshike7171 2014-04-15 20:59
    关注

    Try storing your TLS connection in a new variable of type *tls.Conn. Initiate a handshake and check what ConnectionState() tells.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?