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 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题