13 "golang.org/x/crypto/nacl/box"
14 "golang.org/x/crypto/nacl/secretbox"
15 "golang.org/x/crypto/ripemd160"
17 "github.com/tendermint/go-crypto"
18 wire "github.com/tendermint/go-wire"
19 cmn "github.com/tendermint/tmlibs/common"
23 dataLenSize = 2 // uint16 to describe the length, is <= dataMaxSize
25 totalFrameSize = dataMaxSize + dataLenSize
26 sealedFrameSize = totalFrameSize + secretbox.Overhead
27 authSigMsgSize = (32 + 1) + (64 + 1) // fixed size (length prefixed) byte arrays
30 type authSigMessage struct {
35 // SecretConnection implements net.Conn
36 type SecretConnection struct {
37 conn io.ReadWriteCloser
41 remPubKey crypto.PubKeyEd25519
42 shrSecret *[32]byte // shared secret
45 // MakeSecretConnection performs handshake and returns a new authenticated SecretConnection.
46 func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKeyEd25519) (*SecretConnection, error) {
47 locPubKey := locPrivKey.PubKey().Unwrap().(crypto.PubKeyEd25519)
49 // Generate ephemeral keys for perfect forward secrecy.
50 locEphPub, locEphPriv := genEphKeys()
52 // Write local ephemeral pubkey and receive one too.
53 // NOTE: every 32-byte string is accepted as a Curve25519 public key
54 // (see DJB's Curve25519 paper: http://cr.yp.to/ecdh/curve25519-20060209.pdf)
55 remEphPub, err := shareEphPubKey(conn, locEphPub)
60 // Compute common shared secret.
61 shrSecret := computeSharedSecret(remEphPub, locEphPriv)
63 // Sort by lexical order.
64 loEphPub, hiEphPub := sort32(locEphPub, remEphPub)
66 // Generate nonces to use for secretbox.
67 recvNonce, sendNonce := genNonces(loEphPub, hiEphPub, locEphPub == loEphPub)
69 // Generate common challenge to sign.
70 challenge := genChallenge(loEphPub, hiEphPub)
72 // Construct SecretConnection.
73 sc := &SecretConnection{
81 // Sign the challenge bytes for authentication.
82 locSignature := signChallenge(challenge, locPrivKey)
84 // Share (in secret) each other's pubkey & challenge signature
85 authSigMsg, err := shareAuthSignature(sc, locPubKey, locSignature)
89 remPubKey, remSignature := authSigMsg.Key, authSigMsg.Sig
90 if !remPubKey.VerifyBytes(challenge[:], remSignature) {
91 return nil, errors.New("Challenge verification failed")
94 sc.remPubKey = remPubKey.Unwrap().(crypto.PubKeyEd25519)
98 // CONTRACT: data smaller than dataMaxSize is read atomically.
99 func (sc *SecretConnection) Read(data []byte) (n int, err error) {
100 if 0 < len(sc.recvBuffer) {
101 n_ := copy(data, sc.recvBuffer)
102 sc.recvBuffer = sc.recvBuffer[n_:]
106 sealedFrame := make([]byte, sealedFrameSize)
107 if _, err = io.ReadFull(sc.conn, sealedFrame); err != nil {
112 frame := make([]byte, totalFrameSize)
113 if _, ok := secretbox.Open(frame[:0], sealedFrame, sc.recvNonce, sc.shrSecret); !ok {
114 return n, errors.New("Failed to decrypt SecretConnection")
117 incr2Nonce(sc.recvNonce)
118 chunkLength := binary.BigEndian.Uint16(frame) // read the first two bytes
119 if chunkLength > dataMaxSize {
120 return 0, errors.New("chunkLength is greater than dataMaxSize")
123 chunk := frame[dataLenSize : dataLenSize+chunkLength]
124 n = copy(data, chunk)
125 sc.recvBuffer = chunk[n:]
129 // RemotePubKey returns authenticated remote pubkey
130 func (sc *SecretConnection) RemotePubKey() crypto.PubKeyEd25519 {
134 // Writes encrypted frames of `sealedFrameSize`
135 // CONTRACT: data smaller than dataMaxSize is read atomically.
136 func (sc *SecretConnection) Write(data []byte) (n int, err error) {
139 frame := make([]byte, totalFrameSize)
140 if dataMaxSize < len(data) {
141 chunk = data[:dataMaxSize]
142 data = data[dataMaxSize:]
147 binary.BigEndian.PutUint16(frame, uint16(len(chunk)))
148 copy(frame[dataLenSize:], chunk)
151 sealedFrame := make([]byte, sealedFrameSize)
152 secretbox.Seal(sealedFrame[:0], frame, sc.sendNonce, sc.shrSecret)
153 incr2Nonce(sc.sendNonce)
155 if _, err := sc.conn.Write(sealedFrame); err != nil {
164 // Close implements net.Conn
165 func (sc *SecretConnection) Close() error { return sc.conn.Close() }
167 // LocalAddr implements net.Conn
168 func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() }
170 // RemoteAddr implements net.Conn
171 func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() }
173 // SetDeadline implements net.Conn
174 func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) }
176 // SetReadDeadline implements net.Conn
177 func (sc *SecretConnection) SetReadDeadline(t time.Time) error {
178 return sc.conn.(net.Conn).SetReadDeadline(t)
181 // SetWriteDeadline implements net.Conn
182 func (sc *SecretConnection) SetWriteDeadline(t time.Time) error {
183 return sc.conn.(net.Conn).SetWriteDeadline(t)
186 func computeSharedSecret(remPubKey, locPrivKey *[32]byte) (shrSecret *[32]byte) {
187 shrSecret = new([32]byte)
188 box.Precompute(shrSecret, remPubKey, locPrivKey)
192 func genChallenge(loPubKey, hiPubKey *[32]byte) (challenge *[32]byte) {
193 return hash32(append(loPubKey[:], hiPubKey[:]...))
196 // increment nonce big-endian by 2 with wraparound.
197 func incr2Nonce(nonce *[24]byte) {
202 // increment nonce big-endian by 1 with wraparound.
203 func incrNonce(nonce *[24]byte) {
204 for i := 23; 0 <= i; i-- {
212 func genEphKeys() (ephPub, ephPriv *[32]byte) {
214 ephPub, ephPriv, err = box.GenerateKey(crand.Reader)
216 cmn.PanicCrisis("Could not generate ephemeral keypairs")
221 func genNonces(loPubKey, hiPubKey *[32]byte, locIsLo bool) (*[24]byte, *[24]byte) {
222 nonce1 := hash24(append(loPubKey[:], hiPubKey[:]...))
223 nonce2 := new([24]byte)
224 copy(nonce2[:], nonce1[:])
225 nonce2[len(nonce2)-1] ^= 0x01
227 return nonce1, nonce2
229 return nonce2, nonce1
232 func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKeyEd25519) (signature crypto.SignatureEd25519) {
233 signature = locPrivKey.Sign(challenge[:]).Unwrap().(crypto.SignatureEd25519)
237 func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKeyEd25519, signature crypto.SignatureEd25519) (*authSigMessage, error) {
238 var recvMsg authSigMessage
243 msgBytes := wire.BinaryBytes(authSigMessage{pubKey.Wrap(), signature.Wrap()})
244 _, err1 = sc.Write(msgBytes)
247 readBuffer := make([]byte, authSigMsgSize)
248 _, err2 = io.ReadFull(sc, readBuffer)
252 n := int(0) // not used.
253 recvMsg = wire.ReadBinary(authSigMessage{}, bytes.NewBuffer(readBuffer), authSigMsgSize, &n, &err2).(authSigMessage)
266 func shareEphPubKey(conn io.ReadWriteCloser, locEphPub *[32]byte) (remEphPub *[32]byte, err error) {
271 _, err1 = conn.Write(locEphPub[:])
274 remEphPub = new([32]byte)
275 _, err2 = io.ReadFull(conn, remEphPub[:])
285 return remEphPub, nil
288 func sort32(foo, bar *[32]byte) (*[32]byte, *[32]byte) {
289 if bytes.Compare(foo[:], bar[:]) < 0 {
296 func hash32(input []byte) (res *[32]byte) {
297 hasher := sha256.New()
298 hasher.Write(input) // does not error
299 resSlice := hasher.Sum(nil)
301 copy(res[:], resSlice)
305 // We only fill in the first 20 bytes with ripemd160
306 func hash24(input []byte) (res *[24]byte) {
307 hasher := ripemd160.New()
308 hasher.Write(input) // does not error
309 resSlice := hasher.Sum(nil)
311 copy(res[:], resSlice)