You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

449 lines
13 KiB

p2p: make SecretConnection non-malleable (#3668) ## Issue: This is an approach to fixing secret connection that is more noise-ish than actually noise. but it essentially fixes the problem that #3315 is trying to solve by making the secret connection handshake non-malleable. It's easy to understand and I think will be acceptable to @jaekwon .. the formal reasoning is basically, if the "view" of the transcript between diverges between the sender and the receiver at any point in the protocol, the handshake would terminate. The base protocol of Station to Station mistakenly assumes that if the sender and receiver arrive at shared secret they have the same view. This is only true for a DH on prime order groups. This robustly solves the problem by having each cryptographic operation commit to operators view of the protocol. Another nice thing about a transcript is it provides the basis for "secure" (barring cryptographic breakages, horrible design flaws, or implementation bugs) downgrades, where a backwards compatible handshake can be used to offer newer protocol features/extensions, peers agree to the common subset of what they support, and both sides have to agree on what the other offered for the transcript MAC to verify. With something like Protos/Amino you already get "extensions" for free (TLS uses a simple TLV format https://tools.ietf.org/html/rfc8446#section-4.2 for extensions not too far off from Protos/Amino), so as long as you cryptographically commit to what they contain in the transcript, it should be possible to extend the protocol in a backwards-compatible manner. ## Commits: * Minimal changes to remove malleability of secret connection removes the need to check for lower order points. Breaks compatibility. Secret connections that have no been updated will fail * Remove the redundant blacklist * remove remainders of blacklist in tests to make the code compile again Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Apply suggestions from code review Apply Ismail's error handling Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * fix error check for io.ReadFull Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Bot from GolangCI <42910462+golangcibot@users.noreply.github.com> * update changelog and format the code * move hkdfInit closer to where it's used
5 years ago
p2p: make SecretConnection non-malleable (#3668) ## Issue: This is an approach to fixing secret connection that is more noise-ish than actually noise. but it essentially fixes the problem that #3315 is trying to solve by making the secret connection handshake non-malleable. It's easy to understand and I think will be acceptable to @jaekwon .. the formal reasoning is basically, if the "view" of the transcript between diverges between the sender and the receiver at any point in the protocol, the handshake would terminate. The base protocol of Station to Station mistakenly assumes that if the sender and receiver arrive at shared secret they have the same view. This is only true for a DH on prime order groups. This robustly solves the problem by having each cryptographic operation commit to operators view of the protocol. Another nice thing about a transcript is it provides the basis for "secure" (barring cryptographic breakages, horrible design flaws, or implementation bugs) downgrades, where a backwards compatible handshake can be used to offer newer protocol features/extensions, peers agree to the common subset of what they support, and both sides have to agree on what the other offered for the transcript MAC to verify. With something like Protos/Amino you already get "extensions" for free (TLS uses a simple TLV format https://tools.ietf.org/html/rfc8446#section-4.2 for extensions not too far off from Protos/Amino), so as long as you cryptographically commit to what they contain in the transcript, it should be possible to extend the protocol in a backwards-compatible manner. ## Commits: * Minimal changes to remove malleability of secret connection removes the need to check for lower order points. Breaks compatibility. Secret connections that have no been updated will fail * Remove the redundant blacklist * remove remainders of blacklist in tests to make the code compile again Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Apply suggestions from code review Apply Ismail's error handling Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * fix error check for io.ReadFull Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Bot from GolangCI <42910462+golangcibot@users.noreply.github.com> * update changelog and format the code * move hkdfInit closer to where it's used
5 years ago
p2p: make SecretConnection non-malleable (#3668) ## Issue: This is an approach to fixing secret connection that is more noise-ish than actually noise. but it essentially fixes the problem that #3315 is trying to solve by making the secret connection handshake non-malleable. It's easy to understand and I think will be acceptable to @jaekwon .. the formal reasoning is basically, if the "view" of the transcript between diverges between the sender and the receiver at any point in the protocol, the handshake would terminate. The base protocol of Station to Station mistakenly assumes that if the sender and receiver arrive at shared secret they have the same view. This is only true for a DH on prime order groups. This robustly solves the problem by having each cryptographic operation commit to operators view of the protocol. Another nice thing about a transcript is it provides the basis for "secure" (barring cryptographic breakages, horrible design flaws, or implementation bugs) downgrades, where a backwards compatible handshake can be used to offer newer protocol features/extensions, peers agree to the common subset of what they support, and both sides have to agree on what the other offered for the transcript MAC to verify. With something like Protos/Amino you already get "extensions" for free (TLS uses a simple TLV format https://tools.ietf.org/html/rfc8446#section-4.2 for extensions not too far off from Protos/Amino), so as long as you cryptographically commit to what they contain in the transcript, it should be possible to extend the protocol in a backwards-compatible manner. ## Commits: * Minimal changes to remove malleability of secret connection removes the need to check for lower order points. Breaks compatibility. Secret connections that have no been updated will fail * Remove the redundant blacklist * remove remainders of blacklist in tests to make the code compile again Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Apply suggestions from code review Apply Ismail's error handling Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * fix error check for io.ReadFull Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Bot from GolangCI <42910462+golangcibot@users.noreply.github.com> * update changelog and format the code * move hkdfInit closer to where it's used
5 years ago
p2p: make SecretConnection non-malleable (#3668) ## Issue: This is an approach to fixing secret connection that is more noise-ish than actually noise. but it essentially fixes the problem that #3315 is trying to solve by making the secret connection handshake non-malleable. It's easy to understand and I think will be acceptable to @jaekwon .. the formal reasoning is basically, if the "view" of the transcript between diverges between the sender and the receiver at any point in the protocol, the handshake would terminate. The base protocol of Station to Station mistakenly assumes that if the sender and receiver arrive at shared secret they have the same view. This is only true for a DH on prime order groups. This robustly solves the problem by having each cryptographic operation commit to operators view of the protocol. Another nice thing about a transcript is it provides the basis for "secure" (barring cryptographic breakages, horrible design flaws, or implementation bugs) downgrades, where a backwards compatible handshake can be used to offer newer protocol features/extensions, peers agree to the common subset of what they support, and both sides have to agree on what the other offered for the transcript MAC to verify. With something like Protos/Amino you already get "extensions" for free (TLS uses a simple TLV format https://tools.ietf.org/html/rfc8446#section-4.2 for extensions not too far off from Protos/Amino), so as long as you cryptographically commit to what they contain in the transcript, it should be possible to extend the protocol in a backwards-compatible manner. ## Commits: * Minimal changes to remove malleability of secret connection removes the need to check for lower order points. Breaks compatibility. Secret connections that have no been updated will fail * Remove the redundant blacklist * remove remainders of blacklist in tests to make the code compile again Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Apply suggestions from code review Apply Ismail's error handling Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * fix error check for io.ReadFull Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Bot from GolangCI <42910462+golangcibot@users.noreply.github.com> * update changelog and format the code * move hkdfInit closer to where it's used
5 years ago
p2p: make SecretConnection non-malleable (#3668) ## Issue: This is an approach to fixing secret connection that is more noise-ish than actually noise. but it essentially fixes the problem that #3315 is trying to solve by making the secret connection handshake non-malleable. It's easy to understand and I think will be acceptable to @jaekwon .. the formal reasoning is basically, if the "view" of the transcript between diverges between the sender and the receiver at any point in the protocol, the handshake would terminate. The base protocol of Station to Station mistakenly assumes that if the sender and receiver arrive at shared secret they have the same view. This is only true for a DH on prime order groups. This robustly solves the problem by having each cryptographic operation commit to operators view of the protocol. Another nice thing about a transcript is it provides the basis for "secure" (barring cryptographic breakages, horrible design flaws, or implementation bugs) downgrades, where a backwards compatible handshake can be used to offer newer protocol features/extensions, peers agree to the common subset of what they support, and both sides have to agree on what the other offered for the transcript MAC to verify. With something like Protos/Amino you already get "extensions" for free (TLS uses a simple TLV format https://tools.ietf.org/html/rfc8446#section-4.2 for extensions not too far off from Protos/Amino), so as long as you cryptographically commit to what they contain in the transcript, it should be possible to extend the protocol in a backwards-compatible manner. ## Commits: * Minimal changes to remove malleability of secret connection removes the need to check for lower order points. Breaks compatibility. Secret connections that have no been updated will fail * Remove the redundant blacklist * remove remainders of blacklist in tests to make the code compile again Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Apply suggestions from code review Apply Ismail's error handling Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * fix error check for io.ReadFull Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Bot from GolangCI <42910462+golangcibot@users.noreply.github.com> * update changelog and format the code * move hkdfInit closer to where it's used
5 years ago
p2p: make SecretConnection non-malleable (#3668) ## Issue: This is an approach to fixing secret connection that is more noise-ish than actually noise. but it essentially fixes the problem that #3315 is trying to solve by making the secret connection handshake non-malleable. It's easy to understand and I think will be acceptable to @jaekwon .. the formal reasoning is basically, if the "view" of the transcript between diverges between the sender and the receiver at any point in the protocol, the handshake would terminate. The base protocol of Station to Station mistakenly assumes that if the sender and receiver arrive at shared secret they have the same view. This is only true for a DH on prime order groups. This robustly solves the problem by having each cryptographic operation commit to operators view of the protocol. Another nice thing about a transcript is it provides the basis for "secure" (barring cryptographic breakages, horrible design flaws, or implementation bugs) downgrades, where a backwards compatible handshake can be used to offer newer protocol features/extensions, peers agree to the common subset of what they support, and both sides have to agree on what the other offered for the transcript MAC to verify. With something like Protos/Amino you already get "extensions" for free (TLS uses a simple TLV format https://tools.ietf.org/html/rfc8446#section-4.2 for extensions not too far off from Protos/Amino), so as long as you cryptographically commit to what they contain in the transcript, it should be possible to extend the protocol in a backwards-compatible manner. ## Commits: * Minimal changes to remove malleability of secret connection removes the need to check for lower order points. Breaks compatibility. Secret connections that have no been updated will fail * Remove the redundant blacklist * remove remainders of blacklist in tests to make the code compile again Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Apply suggestions from code review Apply Ismail's error handling Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * fix error check for io.ReadFull Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Bot from GolangCI <42910462+golangcibot@users.noreply.github.com> * update changelog and format the code * move hkdfInit closer to where it's used
5 years ago
p2p: make SecretConnection non-malleable (#3668) ## Issue: This is an approach to fixing secret connection that is more noise-ish than actually noise. but it essentially fixes the problem that #3315 is trying to solve by making the secret connection handshake non-malleable. It's easy to understand and I think will be acceptable to @jaekwon .. the formal reasoning is basically, if the "view" of the transcript between diverges between the sender and the receiver at any point in the protocol, the handshake would terminate. The base protocol of Station to Station mistakenly assumes that if the sender and receiver arrive at shared secret they have the same view. This is only true for a DH on prime order groups. This robustly solves the problem by having each cryptographic operation commit to operators view of the protocol. Another nice thing about a transcript is it provides the basis for "secure" (barring cryptographic breakages, horrible design flaws, or implementation bugs) downgrades, where a backwards compatible handshake can be used to offer newer protocol features/extensions, peers agree to the common subset of what they support, and both sides have to agree on what the other offered for the transcript MAC to verify. With something like Protos/Amino you already get "extensions" for free (TLS uses a simple TLV format https://tools.ietf.org/html/rfc8446#section-4.2 for extensions not too far off from Protos/Amino), so as long as you cryptographically commit to what they contain in the transcript, it should be possible to extend the protocol in a backwards-compatible manner. ## Commits: * Minimal changes to remove malleability of secret connection removes the need to check for lower order points. Breaks compatibility. Secret connections that have no been updated will fail * Remove the redundant blacklist * remove remainders of blacklist in tests to make the code compile again Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Apply suggestions from code review Apply Ismail's error handling Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * fix error check for io.ReadFull Signed-off-by: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Ismail Khoffi <Ismail.Khoffi@gmail.com> * Update p2p/conn/secret_connection.go Co-Authored-By: Bot from GolangCI <42910462+golangcibot@users.noreply.github.com> * update changelog and format the code * move hkdfInit closer to where it's used
5 years ago
  1. package conn
  2. import (
  3. "bytes"
  4. "crypto/cipher"
  5. crand "crypto/rand"
  6. "crypto/sha256"
  7. "crypto/subtle"
  8. "encoding/binary"
  9. "io"
  10. "math"
  11. "net"
  12. "sync"
  13. "time"
  14. pool "github.com/libp2p/go-buffer-pool"
  15. "github.com/pkg/errors"
  16. "golang.org/x/crypto/chacha20poly1305"
  17. "golang.org/x/crypto/curve25519"
  18. "golang.org/x/crypto/hkdf"
  19. "golang.org/x/crypto/nacl/box"
  20. "github.com/tendermint/tendermint/crypto"
  21. "github.com/tendermint/tendermint/crypto/ed25519"
  22. cmn "github.com/tendermint/tendermint/libs/common"
  23. )
  24. // 4 + 1024 == 1028 total frame size
  25. const dataLenSize = 4
  26. const dataMaxSize = 1024
  27. const totalFrameSize = dataMaxSize + dataLenSize
  28. const aeadSizeOverhead = 16 // overhead of poly 1305 authentication tag
  29. const aeadKeySize = chacha20poly1305.KeySize
  30. const aeadNonceSize = chacha20poly1305.NonceSize
  31. var (
  32. ErrSmallOrderRemotePubKey = errors.New("detected low order point from remote peer")
  33. ErrSharedSecretIsZero = errors.New("shared secret is all zeroes")
  34. )
  35. // SecretConnection implements net.Conn.
  36. // It is an implementation of the STS protocol.
  37. // See https://github.com/tendermint/tendermint/blob/0.1/docs/sts-final.pdf for
  38. // details on the protocol.
  39. //
  40. // Consumers of the SecretConnection are responsible for authenticating
  41. // the remote peer's pubkey against known information, like a nodeID.
  42. // Otherwise they are vulnerable to MITM.
  43. // (TODO(ismail): see also https://github.com/tendermint/tendermint/issues/3010)
  44. type SecretConnection struct {
  45. // immutable
  46. recvAead cipher.AEAD
  47. sendAead cipher.AEAD
  48. remPubKey crypto.PubKey
  49. conn io.ReadWriteCloser
  50. // net.Conn must be thread safe:
  51. // https://golang.org/pkg/net/#Conn.
  52. // Since we have internal mutable state,
  53. // we need mtxs. But recv and send states
  54. // are independent, so we can use two mtxs.
  55. // All .Read are covered by recvMtx,
  56. // all .Write are covered by sendMtx.
  57. recvMtx sync.Mutex
  58. recvBuffer []byte
  59. recvNonce *[aeadNonceSize]byte
  60. sendMtx sync.Mutex
  61. sendNonce *[aeadNonceSize]byte
  62. }
  63. // MakeSecretConnection performs handshake and returns a new authenticated
  64. // SecretConnection.
  65. // Returns nil if there is an error in handshake.
  66. // Caller should call conn.Close()
  67. // See docs/sts-final.pdf for more information.
  68. func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKey) (*SecretConnection, error) {
  69. var (
  70. hash = sha256.New
  71. hdkfState = new([32]byte)
  72. locPubKey = locPrivKey.PubKey()
  73. )
  74. // Generate ephemeral keys for perfect forward secrecy.
  75. locEphPub, locEphPriv := genEphKeys()
  76. // Write local ephemeral pubkey and receive one too.
  77. // NOTE: every 32-byte string is accepted as a Curve25519 public key (see
  78. // DJB's Curve25519 paper: http://cr.yp.to/ecdh/curve25519-20060209.pdf)
  79. remEphPub, err := shareEphPubKey(conn, locEphPub)
  80. if err != nil {
  81. return nil, err
  82. }
  83. // Sort by lexical order.
  84. loEphPub, hiEphPub := sort32(locEphPub, remEphPub)
  85. hkdfInit := hkdf.New(hash, []byte("INIT_HANDSHAKE"), nil, []byte("TENDERMINT_SECRET_CONNECTION_TRANSCRIPT_HASH"))
  86. if _, err := io.ReadFull(hkdfInit, hdkfState[:]); err != nil {
  87. return nil, err
  88. }
  89. hkdfLoEphPub := hkdf.New(hash, loEphPub[:], hdkfState[:], []byte("TENDERMINT_SECRET_CONNECTION_TRANSCRIPT_HASH"))
  90. if _, err := io.ReadFull(hkdfLoEphPub, hdkfState[:]); err != nil {
  91. return nil, err
  92. }
  93. hkdfHiEphPub := hkdf.New(hash, hiEphPub[:], hdkfState[:], []byte("TENDERMINT_SECRET_CONNECTION_TRANSCRIPT_HASH"))
  94. // Check if the local ephemeral public key was the least, lexicographically
  95. // sorted.
  96. locIsLeast := bytes.Equal(locEphPub[:], loEphPub[:])
  97. // Compute common diffie hellman secret using X25519.
  98. dhSecret, err := computeDHSecret(remEphPub, locEphPriv)
  99. if err != nil {
  100. return nil, err
  101. }
  102. if _, err := io.ReadFull(hkdfHiEphPub, hdkfState[:]); err != nil {
  103. return nil, err
  104. }
  105. hkdfSecret := hkdf.New(hash, dhSecret[:], hdkfState[:], []byte("TENDERMINT_SECRET_CONNECTION_TRANSCRIPT_HASH"))
  106. if _, err := io.ReadFull(hkdfSecret, hdkfState[:]); err != nil {
  107. return nil, err
  108. }
  109. // Generate the secret used for receiving, sending, challenge via HKDF-SHA2
  110. // on the transcript state (which itself also uses HKDF-SHA2 to derive a key
  111. // from the dhSecret).
  112. recvSecret, sendSecret, challenge := deriveSecretAndChallenge(hdkfState, locIsLeast)
  113. sendAead, err := chacha20poly1305.New(sendSecret[:])
  114. if err != nil {
  115. return nil, errors.New("invalid send SecretConnection Key")
  116. }
  117. recvAead, err := chacha20poly1305.New(recvSecret[:])
  118. if err != nil {
  119. return nil, errors.New("invalid receive SecretConnection Key")
  120. }
  121. sc := &SecretConnection{
  122. conn: conn,
  123. recvBuffer: nil,
  124. recvNonce: new([aeadNonceSize]byte),
  125. sendNonce: new([aeadNonceSize]byte),
  126. recvAead: recvAead,
  127. sendAead: sendAead,
  128. }
  129. // Sign the challenge bytes for authentication.
  130. locSignature := signChallenge(challenge, locPrivKey)
  131. // Share (in secret) each other's pubkey & challenge signature
  132. authSigMsg, err := shareAuthSignature(sc, locPubKey, locSignature)
  133. if err != nil {
  134. return nil, err
  135. }
  136. remPubKey, remSignature := authSigMsg.Key, authSigMsg.Sig
  137. if _, ok := remPubKey.(ed25519.PubKeyEd25519); !ok {
  138. return nil, errors.Errorf("expected ed25519 pubkey, got %T", remPubKey)
  139. }
  140. if !remPubKey.VerifyBytes(challenge[:], remSignature) {
  141. return nil, errors.New("challenge verification failed")
  142. }
  143. // We've authorized.
  144. sc.remPubKey = remPubKey
  145. return sc, nil
  146. }
  147. // RemotePubKey returns authenticated remote pubkey
  148. func (sc *SecretConnection) RemotePubKey() crypto.PubKey {
  149. return sc.remPubKey
  150. }
  151. // Writes encrypted frames of `totalFrameSize + aeadSizeOverhead`.
  152. // CONTRACT: data smaller than dataMaxSize is written atomically.
  153. func (sc *SecretConnection) Write(data []byte) (n int, err error) {
  154. sc.sendMtx.Lock()
  155. defer sc.sendMtx.Unlock()
  156. for 0 < len(data) {
  157. if err := func() error {
  158. var sealedFrame = pool.Get(aeadSizeOverhead + totalFrameSize)
  159. var frame = pool.Get(totalFrameSize)
  160. defer func() {
  161. pool.Put(sealedFrame)
  162. pool.Put(frame)
  163. }()
  164. var chunk []byte
  165. if dataMaxSize < len(data) {
  166. chunk = data[:dataMaxSize]
  167. data = data[dataMaxSize:]
  168. } else {
  169. chunk = data
  170. data = nil
  171. }
  172. chunkLength := len(chunk)
  173. binary.LittleEndian.PutUint32(frame, uint32(chunkLength))
  174. copy(frame[dataLenSize:], chunk)
  175. // encrypt the frame
  176. sc.sendAead.Seal(sealedFrame[:0], sc.sendNonce[:], frame, nil)
  177. incrNonce(sc.sendNonce)
  178. // end encryption
  179. _, err = sc.conn.Write(sealedFrame)
  180. if err != nil {
  181. return err
  182. }
  183. n += len(chunk)
  184. return nil
  185. }(); err != nil {
  186. return n, err
  187. }
  188. }
  189. return n, err
  190. }
  191. // CONTRACT: data smaller than dataMaxSize is read atomically.
  192. func (sc *SecretConnection) Read(data []byte) (n int, err error) {
  193. sc.recvMtx.Lock()
  194. defer sc.recvMtx.Unlock()
  195. // read off and update the recvBuffer, if non-empty
  196. if 0 < len(sc.recvBuffer) {
  197. n = copy(data, sc.recvBuffer)
  198. sc.recvBuffer = sc.recvBuffer[n:]
  199. return
  200. }
  201. // read off the conn
  202. var sealedFrame = pool.Get(aeadSizeOverhead + totalFrameSize)
  203. defer pool.Put(sealedFrame)
  204. _, err = io.ReadFull(sc.conn, sealedFrame)
  205. if err != nil {
  206. return
  207. }
  208. // decrypt the frame.
  209. // reads and updates the sc.recvNonce
  210. var frame = pool.Get(totalFrameSize)
  211. defer pool.Put(frame)
  212. _, err = sc.recvAead.Open(frame[:0], sc.recvNonce[:], sealedFrame, nil)
  213. if err != nil {
  214. return n, errors.New("failed to decrypt SecretConnection")
  215. }
  216. incrNonce(sc.recvNonce)
  217. // end decryption
  218. // copy checkLength worth into data,
  219. // set recvBuffer to the rest.
  220. var chunkLength = binary.LittleEndian.Uint32(frame) // read the first four bytes
  221. if chunkLength > dataMaxSize {
  222. return 0, errors.New("chunkLength is greater than dataMaxSize")
  223. }
  224. var chunk = frame[dataLenSize : dataLenSize+chunkLength]
  225. n = copy(data, chunk)
  226. if n < len(chunk) {
  227. sc.recvBuffer = make([]byte, len(chunk)-n)
  228. copy(sc.recvBuffer, chunk[n:])
  229. }
  230. return n, err
  231. }
  232. // Implements net.Conn
  233. // nolint
  234. func (sc *SecretConnection) Close() error { return sc.conn.Close() }
  235. func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() }
  236. func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() }
  237. func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) }
  238. func (sc *SecretConnection) SetReadDeadline(t time.Time) error {
  239. return sc.conn.(net.Conn).SetReadDeadline(t)
  240. }
  241. func (sc *SecretConnection) SetWriteDeadline(t time.Time) error {
  242. return sc.conn.(net.Conn).SetWriteDeadline(t)
  243. }
  244. func genEphKeys() (ephPub, ephPriv *[32]byte) {
  245. var err error
  246. // TODO: Probably not a problem but ask Tony: different from the rust implementation (uses x25519-dalek),
  247. // we do not "clamp" the private key scalar:
  248. // see: https://github.com/dalek-cryptography/x25519-dalek/blob/34676d336049df2bba763cc076a75e47ae1f170f/src/x25519.rs#L56-L74
  249. ephPub, ephPriv, err = box.GenerateKey(crand.Reader)
  250. if err != nil {
  251. panic("Could not generate ephemeral key-pair")
  252. }
  253. return
  254. }
  255. func shareEphPubKey(conn io.ReadWriter, locEphPub *[32]byte) (remEphPub *[32]byte, err error) {
  256. // Send our pubkey and receive theirs in tandem.
  257. var trs, _ = cmn.Parallel(
  258. func(_ int) (val interface{}, abort bool, err error) {
  259. var _, err1 = cdc.MarshalBinaryLengthPrefixedWriter(conn, locEphPub)
  260. if err1 != nil {
  261. return nil, true, err1 // abort
  262. }
  263. return nil, false, nil
  264. },
  265. func(_ int) (val interface{}, abort bool, err error) {
  266. var _remEphPub [32]byte
  267. var _, err2 = cdc.UnmarshalBinaryLengthPrefixedReader(conn, &_remEphPub, 1024*1024) // TODO
  268. if err2 != nil {
  269. return nil, true, err2 // abort
  270. }
  271. return _remEphPub, false, nil
  272. },
  273. )
  274. // If error:
  275. if trs.FirstError() != nil {
  276. err = trs.FirstError()
  277. return
  278. }
  279. // Otherwise:
  280. var _remEphPub = trs.FirstValue().([32]byte)
  281. return &_remEphPub, nil
  282. }
  283. func deriveSecretAndChallenge(
  284. dhSecret *[32]byte,
  285. locIsLeast bool,
  286. ) (recvSecret, sendSecret *[aeadKeySize]byte, challenge *[32]byte) {
  287. hash := sha256.New
  288. hkdf := hkdf.New(hash, dhSecret[:], nil, []byte("TENDERMINT_SECRET_CONNECTION_KEY_AND_CHALLENGE_GEN"))
  289. // get enough data for 2 aead keys, and a 32 byte challenge
  290. res := new([2*aeadKeySize + 32]byte)
  291. _, err := io.ReadFull(hkdf, res[:])
  292. if err != nil {
  293. panic(err)
  294. }
  295. challenge = new([32]byte)
  296. recvSecret = new([aeadKeySize]byte)
  297. sendSecret = new([aeadKeySize]byte)
  298. // Use the last 32 bytes as the challenge
  299. copy(challenge[:], res[2*aeadKeySize:2*aeadKeySize+32])
  300. // bytes 0 through aeadKeySize - 1 are one aead key.
  301. // bytes aeadKeySize through 2*aeadKeySize -1 are another aead key.
  302. // which key corresponds to sending and receiving key depends on whether
  303. // the local key is less than the remote key.
  304. if locIsLeast {
  305. copy(recvSecret[:], res[0:aeadKeySize])
  306. copy(sendSecret[:], res[aeadKeySize:aeadKeySize*2])
  307. } else {
  308. copy(sendSecret[:], res[0:aeadKeySize])
  309. copy(recvSecret[:], res[aeadKeySize:aeadKeySize*2])
  310. }
  311. return
  312. }
  313. // computeDHSecret computes a Diffie-Hellman shared secret key
  314. // from our own local private key and the other's public key.
  315. //
  316. // It returns an error if the computed shared secret is all zeroes.
  317. func computeDHSecret(remPubKey, locPrivKey *[32]byte) (shrKey *[32]byte, err error) {
  318. shrKey = new([32]byte)
  319. curve25519.ScalarMult(shrKey, locPrivKey, remPubKey)
  320. // reject if the returned shared secret is all zeroes
  321. // related to: https://github.com/tendermint/tendermint/issues/3010
  322. zero := new([32]byte)
  323. if subtle.ConstantTimeCompare(shrKey[:], zero[:]) == 1 {
  324. return nil, ErrSharedSecretIsZero
  325. }
  326. return
  327. }
  328. func sort32(foo, bar *[32]byte) (lo, hi *[32]byte) {
  329. if bytes.Compare(foo[:], bar[:]) < 0 {
  330. lo = foo
  331. hi = bar
  332. } else {
  333. lo = bar
  334. hi = foo
  335. }
  336. return
  337. }
  338. func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKey) (signature []byte) {
  339. signature, err := locPrivKey.Sign(challenge[:])
  340. // TODO(ismail): let signChallenge return an error instead
  341. if err != nil {
  342. panic(err)
  343. }
  344. return
  345. }
  346. type authSigMessage struct {
  347. Key crypto.PubKey
  348. Sig []byte
  349. }
  350. func shareAuthSignature(sc io.ReadWriter, pubKey crypto.PubKey, signature []byte) (recvMsg authSigMessage, err error) {
  351. // Send our info and receive theirs in tandem.
  352. var trs, _ = cmn.Parallel(
  353. func(_ int) (val interface{}, abort bool, err error) {
  354. var _, err1 = cdc.MarshalBinaryLengthPrefixedWriter(sc, authSigMessage{pubKey, signature})
  355. if err1 != nil {
  356. return nil, true, err1 // abort
  357. }
  358. return nil, false, nil
  359. },
  360. func(_ int) (val interface{}, abort bool, err error) {
  361. var _recvMsg authSigMessage
  362. var _, err2 = cdc.UnmarshalBinaryLengthPrefixedReader(sc, &_recvMsg, 1024*1024) // TODO
  363. if err2 != nil {
  364. return nil, true, err2 // abort
  365. }
  366. return _recvMsg, false, nil
  367. },
  368. )
  369. // If error:
  370. if trs.FirstError() != nil {
  371. err = trs.FirstError()
  372. return
  373. }
  374. var _recvMsg = trs.FirstValue().(authSigMessage)
  375. return _recvMsg, nil
  376. }
  377. //--------------------------------------------------------------------------------
  378. // Increment nonce little-endian by 1 with wraparound.
  379. // Due to chacha20poly1305 expecting a 12 byte nonce we do not use the first four
  380. // bytes. We only increment a 64 bit unsigned int in the remaining 8 bytes
  381. // (little-endian in nonce[4:]).
  382. func incrNonce(nonce *[aeadNonceSize]byte) {
  383. counter := binary.LittleEndian.Uint64(nonce[4:])
  384. if counter == math.MaxUint64 {
  385. // Terminates the session and makes sure the nonce would not re-used.
  386. // See https://github.com/tendermint/tendermint/issues/3531
  387. panic("can't increase nonce without overflow")
  388. }
  389. counter++
  390. binary.LittleEndian.PutUint64(nonce[4:], counter)
  391. }