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?