13 log "github.com/sirupsen/logrus"
14 "golang.org/x/crypto/nacl/box"
15 "golang.org/x/crypto/nacl/secretbox"
16 "golang.org/x/crypto/ripemd160"
18 "github.com/tendermint/go-crypto"
19 wire "github.com/tendermint/go-wire"
20 cmn "github.com/tendermint/tmlibs/common"
24 dataLenSize = 2 // uint16 to describe the length, is <= dataMaxSize
26 totalFrameSize = dataMaxSize + dataLenSize
27 sealedFrameSize = totalFrameSize + secretbox.Overhead
28 authSigMsgSize = (32 + 1) + (64 + 1) // fixed size (length prefixed) byte arrays
31 type authSigMessage struct {
36 // SecretConnection implements net.Conn
37 type SecretConnection struct {
38 conn io.ReadWriteCloser
42 remPubKey crypto.PubKeyEd25519
43 shrSecret *[32]byte // shared secret
46 // MakeSecretConnection performs handshake and returns a new authenticated SecretConnection.
47 func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKeyEd25519) (*SecretConnection, error) {
48 locPubKey := locPrivKey.PubKey().Unwrap().(crypto.PubKeyEd25519)
50 // Generate ephemeral keys for perfect forward secrecy.
51 locEphPub, locEphPriv := genEphKeys()
53 // Write local ephemeral pubkey and receive one too.
54 // NOTE: every 32-byte string is accepted as a Curve25519 public key
55 // (see DJB's Curve25519 paper: http://cr.yp.to/ecdh/curve25519-20060209.pdf)
56 remEphPub, err := shareEphPubKey(conn, locEphPub)
61 // Compute common shared secret.
62 shrSecret := computeSharedSecret(remEphPub, locEphPriv)
64 // Sort by lexical order.
65 loEphPub, hiEphPub := sort32(locEphPub, remEphPub)
67 // Generate nonces to use for secretbox.
68 recvNonce, sendNonce := genNonces(loEphPub, hiEphPub, locEphPub == loEphPub)
70 // Generate common challenge to sign.
71 challenge := genChallenge(loEphPub, hiEphPub)
73 // Construct SecretConnection.
74 sc := &SecretConnection{
82 // Sign the challenge bytes for authentication.
83 locSignature := signChallenge(challenge, locPrivKey)
85 // Share (in secret) each other's pubkey & challenge signature
86 authSigMsg, err := shareAuthSignature(sc, locPubKey, locSignature)
90 remPubKey, remSignature := authSigMsg.Key, authSigMsg.Sig
91 if !remPubKey.VerifyBytes(challenge[:], remSignature) {
92 return nil, errors.New("Challenge verification failed")
95 sc.remPubKey = remPubKey.Unwrap().(crypto.PubKeyEd25519)
99 // CONTRACT: data smaller than dataMaxSize is read atomically.
100 func (sc *SecretConnection) Read(data []byte) (n int, err error) {
101 if 0 < len(sc.recvBuffer) {
102 n_ := copy(data, sc.recvBuffer)
103 sc.recvBuffer = sc.recvBuffer[n_:]
107 sealedFrame := make([]byte, sealedFrameSize)
108 if _, err = io.ReadFull(sc.conn, sealedFrame); err != nil {
113 frame := make([]byte, totalFrameSize)
114 if _, ok := secretbox.Open(frame[:0], sealedFrame, sc.recvNonce, sc.shrSecret); !ok {
115 return n, errors.New("Failed to decrypt SecretConnection")
118 incr2Nonce(sc.recvNonce)
119 chunkLength := binary.BigEndian.Uint16(frame) // read the first two bytes
120 if chunkLength > dataMaxSize {
121 return 0, errors.New("chunkLength is greater than dataMaxSize")
124 chunk := frame[dataLenSize : dataLenSize+chunkLength]
125 n = copy(data, chunk)
126 sc.recvBuffer = chunk[n:]
130 // RemotePubKey returns authenticated remote pubkey
131 func (sc *SecretConnection) RemotePubKey() crypto.PubKeyEd25519 {
135 // Writes encrypted frames of `sealedFrameSize`
136 // CONTRACT: data smaller than dataMaxSize is read atomically.
137 func (sc *SecretConnection) Write(data []byte) (n int, err error) {
140 frame := make([]byte, totalFrameSize)
141 if dataMaxSize < len(data) {
142 chunk = data[:dataMaxSize]
143 data = data[dataMaxSize:]
148 binary.BigEndian.PutUint16(frame, uint16(len(chunk)))
149 copy(frame[dataLenSize:], chunk)
152 sealedFrame := make([]byte, sealedFrameSize)
153 secretbox.Seal(sealedFrame[:0], frame, sc.sendNonce, sc.shrSecret)
154 incr2Nonce(sc.sendNonce)
156 if _, err := sc.conn.Write(sealedFrame); err != nil {
165 // Close implements net.Conn
166 func (sc *SecretConnection) Close() error { return sc.conn.Close() }
168 // LocalAddr implements net.Conn
169 func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() }
171 // RemoteAddr implements net.Conn
172 func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() }
174 // SetDeadline implements net.Conn
175 func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) }
177 // SetReadDeadline implements net.Conn
178 func (sc *SecretConnection) SetReadDeadline(t time.Time) error {
179 return sc.conn.(net.Conn).SetReadDeadline(t)
182 // SetWriteDeadline implements net.Conn
183 func (sc *SecretConnection) SetWriteDeadline(t time.Time) error {
184 return sc.conn.(net.Conn).SetWriteDeadline(t)
187 func computeSharedSecret(remPubKey, locPrivKey *[32]byte) (shrSecret *[32]byte) {
188 shrSecret = new([32]byte)
189 box.Precompute(shrSecret, remPubKey, locPrivKey)
193 func genChallenge(loPubKey, hiPubKey *[32]byte) (challenge *[32]byte) {
194 return hash32(append(loPubKey[:], hiPubKey[:]...))
197 // increment nonce big-endian by 2 with wraparound.
198 func incr2Nonce(nonce *[24]byte) {
203 // increment nonce big-endian by 1 with wraparound.
204 func incrNonce(nonce *[24]byte) {
205 for i := 23; 0 <= i; i-- {
213 func genEphKeys() (ephPub, ephPriv *[32]byte) {
215 ephPub, ephPriv, err = box.GenerateKey(crand.Reader)
217 log.Panic("Could not generate ephemeral keypairs")
222 func genNonces(loPubKey, hiPubKey *[32]byte, locIsLo bool) (*[24]byte, *[24]byte) {
223 nonce1 := hash24(append(loPubKey[:], hiPubKey[:]...))
224 nonce2 := new([24]byte)
225 copy(nonce2[:], nonce1[:])
226 nonce2[len(nonce2)-1] ^= 0x01
228 return nonce1, nonce2
230 return nonce2, nonce1
233 func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKeyEd25519) (signature crypto.SignatureEd25519) {
234 signature = locPrivKey.Sign(challenge[:]).Unwrap().(crypto.SignatureEd25519)
238 func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKeyEd25519, signature crypto.SignatureEd25519) (*authSigMessage, error) {
239 var recvMsg authSigMessage
244 msgBytes := wire.BinaryBytes(authSigMessage{pubKey.Wrap(), signature.Wrap()})
245 _, err1 = sc.Write(msgBytes)
248 readBuffer := make([]byte, authSigMsgSize)
249 _, err2 = io.ReadFull(sc, readBuffer)
253 n := int(0) // not used.
254 recvMsg = wire.ReadBinary(authSigMessage{}, bytes.NewBuffer(readBuffer), authSigMsgSize, &n, &err2).(authSigMessage)
267 func shareEphPubKey(conn io.ReadWriteCloser, locEphPub *[32]byte) (remEphPub *[32]byte, err error) {
272 _, err1 = conn.Write(locEphPub[:])
275 remEphPub = new([32]byte)
276 _, err2 = io.ReadFull(conn, remEphPub[:])
286 return remEphPub, nil
289 func sort32(foo, bar *[32]byte) (*[32]byte, *[32]byte) {
290 if bytes.Compare(foo[:], bar[:]) < 0 {
297 func hash32(input []byte) (res *[32]byte) {
298 hasher := sha256.New()
299 hasher.Write(input) // does not error
300 resSlice := hasher.Sum(nil)
302 copy(res[:], resSlice)
306 // We only fill in the first 20 bytes with ripemd160
307 func hash24(input []byte) (res *[24]byte) {
308 hasher := ripemd160.New()
309 hasher.Write(input) // does not error
310 resSlice := hasher.Sum(nil)
312 copy(res[:], resSlice)