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.

442 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
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. "encoding/binary"
  8. "io"
  9. "math"
  10. "net"
  11. "sync"
  12. "time"
  13. "github.com/gtank/merlin"
  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. "github.com/tendermint/tendermint/libs/async"
  23. )
  24. // 4 + 1024 == 1028 total frame size
  25. const (
  26. dataLenSize = 4
  27. dataMaxSize = 1024
  28. totalFrameSize = dataMaxSize + dataLenSize
  29. aeadSizeOverhead = 16 // overhead of poly 1305 authentication tag
  30. aeadKeySize = chacha20poly1305.KeySize
  31. aeadNonceSize = chacha20poly1305.NonceSize
  32. )
  33. var (
  34. ErrSmallOrderRemotePubKey = errors.New("detected low order point from remote peer")
  35. labelEphemeralLowerPublicKey = []byte("EPHEMERAL_LOWER_PUBLIC_KEY")
  36. labelEphemeralUpperPublicKey = []byte("EPHEMERAL_UPPER_PUBLIC_KEY")
  37. labelDHSecret = []byte("DH_SECRET")
  38. labelSecretConnectionMac = []byte("SECRET_CONNECTION_MAC")
  39. secretConnKeyAndChallengeGen = []byte("TENDERMINT_SECRET_CONNECTION_KEY_AND_CHALLENGE_GEN")
  40. )
  41. // SecretConnection implements net.Conn.
  42. // It is an implementation of the STS protocol.
  43. // See https://github.com/tendermint/tendermint/blob/0.1/docs/sts-final.pdf for
  44. // details on the protocol.
  45. //
  46. // Consumers of the SecretConnection are responsible for authenticating
  47. // the remote peer's pubkey against known information, like a nodeID.
  48. // Otherwise they are vulnerable to MITM.
  49. // (TODO(ismail): see also https://github.com/tendermint/tendermint/issues/3010)
  50. type SecretConnection struct {
  51. // immutable
  52. recvAead cipher.AEAD
  53. sendAead cipher.AEAD
  54. remPubKey crypto.PubKey
  55. conn io.ReadWriteCloser
  56. // net.Conn must be thread safe:
  57. // https://golang.org/pkg/net/#Conn.
  58. // Since we have internal mutable state,
  59. // we need mtxs. But recv and send states
  60. // are independent, so we can use two mtxs.
  61. // All .Read are covered by recvMtx,
  62. // all .Write are covered by sendMtx.
  63. recvMtx sync.Mutex
  64. recvBuffer []byte
  65. recvNonce *[aeadNonceSize]byte
  66. sendMtx sync.Mutex
  67. sendNonce *[aeadNonceSize]byte
  68. }
  69. // MakeSecretConnection performs handshake and returns a new authenticated
  70. // SecretConnection.
  71. // Returns nil if there is an error in handshake.
  72. // Caller should call conn.Close()
  73. // See docs/sts-final.pdf for more information.
  74. func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKey) (*SecretConnection, error) {
  75. var (
  76. locPubKey = locPrivKey.PubKey()
  77. )
  78. // Generate ephemeral keys for perfect forward secrecy.
  79. locEphPub, locEphPriv := genEphKeys()
  80. // Write local ephemeral pubkey and receive one too.
  81. // NOTE: every 32-byte string is accepted as a Curve25519 public key (see
  82. // DJB's Curve25519 paper: http://cr.yp.to/ecdh/curve25519-20060209.pdf)
  83. remEphPub, err := shareEphPubKey(conn, locEphPub)
  84. if err != nil {
  85. return nil, err
  86. }
  87. // Sort by lexical order.
  88. loEphPub, hiEphPub := sort32(locEphPub, remEphPub)
  89. transcript := merlin.NewTranscript("TENDERMINT_SECRET_CONNECTION_TRANSCRIPT_HASH")
  90. transcript.AppendMessage(labelEphemeralLowerPublicKey, loEphPub[:])
  91. transcript.AppendMessage(labelEphemeralUpperPublicKey, hiEphPub[:])
  92. // Check if the local ephemeral public key was the least, lexicographically
  93. // sorted.
  94. locIsLeast := bytes.Equal(locEphPub[:], loEphPub[:])
  95. // Compute common diffie hellman secret using X25519.
  96. dhSecret, err := computeDHSecret(remEphPub, locEphPriv)
  97. if err != nil {
  98. return nil, err
  99. }
  100. transcript.AppendMessage(labelDHSecret, dhSecret[:])
  101. // Generate the secret used for receiving, sending, challenge via HKDF-SHA2
  102. // on the transcript state (which itself also uses HKDF-SHA2 to derive a key
  103. // from the dhSecret).
  104. recvSecret, sendSecret := deriveSecrets(dhSecret, locIsLeast)
  105. const challengeSize = 32
  106. var challenge [challengeSize]byte
  107. challengeSlice := transcript.ExtractBytes(labelSecretConnectionMac, challengeSize)
  108. copy(challenge[:], challengeSlice[0:challengeSize])
  109. sendAead, err := chacha20poly1305.New(sendSecret[:])
  110. if err != nil {
  111. return nil, errors.New("invalid send SecretConnection Key")
  112. }
  113. recvAead, err := chacha20poly1305.New(recvSecret[:])
  114. if err != nil {
  115. return nil, errors.New("invalid receive SecretConnection Key")
  116. }
  117. sc := &SecretConnection{
  118. conn: conn,
  119. recvBuffer: nil,
  120. recvNonce: new([aeadNonceSize]byte),
  121. sendNonce: new([aeadNonceSize]byte),
  122. recvAead: recvAead,
  123. sendAead: sendAead,
  124. }
  125. // Sign the challenge bytes for authentication.
  126. locSignature, err := signChallenge(&challenge, locPrivKey)
  127. if err != nil {
  128. return nil, err
  129. }
  130. // Share (in secret) each other's pubkey & challenge signature
  131. authSigMsg, err := shareAuthSignature(sc, locPubKey, locSignature)
  132. if err != nil {
  133. return nil, err
  134. }
  135. remPubKey, remSignature := authSigMsg.Key, authSigMsg.Sig
  136. if _, ok := remPubKey.(ed25519.PubKeyEd25519); !ok {
  137. return nil, errors.Errorf("expected ed25519 pubkey, got %T", remPubKey)
  138. }
  139. if !remPubKey.VerifyBytes(challenge[:], remSignature) {
  140. return nil, errors.New("challenge verification failed")
  141. }
  142. // We've authorized.
  143. sc.remPubKey = remPubKey
  144. return sc, nil
  145. }
  146. // RemotePubKey returns authenticated remote pubkey
  147. func (sc *SecretConnection) RemotePubKey() crypto.PubKey {
  148. return sc.remPubKey
  149. }
  150. // Writes encrypted frames of `totalFrameSize + aeadSizeOverhead`.
  151. // CONTRACT: data smaller than dataMaxSize is written atomically.
  152. func (sc *SecretConnection) Write(data []byte) (n int, err error) {
  153. sc.sendMtx.Lock()
  154. defer sc.sendMtx.Unlock()
  155. for 0 < len(data) {
  156. if err := func() error {
  157. var sealedFrame = pool.Get(aeadSizeOverhead + totalFrameSize)
  158. var frame = pool.Get(totalFrameSize)
  159. defer func() {
  160. pool.Put(sealedFrame)
  161. pool.Put(frame)
  162. }()
  163. var chunk []byte
  164. if dataMaxSize < len(data) {
  165. chunk = data[:dataMaxSize]
  166. data = data[dataMaxSize:]
  167. } else {
  168. chunk = data
  169. data = nil
  170. }
  171. chunkLength := len(chunk)
  172. binary.LittleEndian.PutUint32(frame, uint32(chunkLength))
  173. copy(frame[dataLenSize:], chunk)
  174. // encrypt the frame
  175. sc.sendAead.Seal(sealedFrame[:0], sc.sendNonce[:], frame, nil)
  176. incrNonce(sc.sendNonce)
  177. // end encryption
  178. _, err = sc.conn.Write(sealedFrame)
  179. if err != nil {
  180. return err
  181. }
  182. n += len(chunk)
  183. return nil
  184. }(); err != nil {
  185. return n, err
  186. }
  187. }
  188. return n, err
  189. }
  190. // CONTRACT: data smaller than dataMaxSize is read atomically.
  191. func (sc *SecretConnection) Read(data []byte) (n int, err error) {
  192. sc.recvMtx.Lock()
  193. defer sc.recvMtx.Unlock()
  194. // read off and update the recvBuffer, if non-empty
  195. if 0 < len(sc.recvBuffer) {
  196. n = copy(data, sc.recvBuffer)
  197. sc.recvBuffer = sc.recvBuffer[n:]
  198. return
  199. }
  200. // read off the conn
  201. var sealedFrame = pool.Get(aeadSizeOverhead + totalFrameSize)
  202. defer pool.Put(sealedFrame)
  203. _, err = io.ReadFull(sc.conn, sealedFrame)
  204. if err != nil {
  205. return
  206. }
  207. // decrypt the frame.
  208. // reads and updates the sc.recvNonce
  209. var frame = pool.Get(totalFrameSize)
  210. defer pool.Put(frame)
  211. _, err = sc.recvAead.Open(frame[:0], sc.recvNonce[:], sealedFrame, nil)
  212. if err != nil {
  213. return n, errors.New("failed to decrypt SecretConnection")
  214. }
  215. incrNonce(sc.recvNonce)
  216. // end decryption
  217. // copy checkLength worth into data,
  218. // set recvBuffer to the rest.
  219. var chunkLength = binary.LittleEndian.Uint32(frame) // read the first four bytes
  220. if chunkLength > dataMaxSize {
  221. return 0, errors.New("chunkLength is greater than dataMaxSize")
  222. }
  223. var chunk = frame[dataLenSize : dataLenSize+chunkLength]
  224. n = copy(data, chunk)
  225. if n < len(chunk) {
  226. sc.recvBuffer = make([]byte, len(chunk)-n)
  227. copy(sc.recvBuffer, chunk[n:])
  228. }
  229. return n, err
  230. }
  231. // Implements net.Conn
  232. // nolint
  233. func (sc *SecretConnection) Close() error { return sc.conn.Close() }
  234. func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() }
  235. func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() }
  236. func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) }
  237. func (sc *SecretConnection) SetReadDeadline(t time.Time) error {
  238. return sc.conn.(net.Conn).SetReadDeadline(t)
  239. }
  240. func (sc *SecretConnection) SetWriteDeadline(t time.Time) error {
  241. return sc.conn.(net.Conn).SetWriteDeadline(t)
  242. }
  243. func genEphKeys() (ephPub, ephPriv *[32]byte) {
  244. var err error
  245. // TODO: Probably not a problem but ask Tony: different from the rust implementation (uses x25519-dalek),
  246. // we do not "clamp" the private key scalar:
  247. // see: https://github.com/dalek-cryptography/x25519-dalek/blob/34676d336049df2bba763cc076a75e47ae1f170f/src/x25519.rs#L56-L74
  248. ephPub, ephPriv, err = box.GenerateKey(crand.Reader)
  249. if err != nil {
  250. panic("Could not generate ephemeral key-pair")
  251. }
  252. return
  253. }
  254. func shareEphPubKey(conn io.ReadWriter, locEphPub *[32]byte) (remEphPub *[32]byte, err error) {
  255. // Send our pubkey and receive theirs in tandem.
  256. var trs, _ = async.Parallel(
  257. func(_ int) (val interface{}, abort bool, err error) {
  258. var _, err1 = cdc.MarshalBinaryLengthPrefixedWriter(conn, locEphPub)
  259. if err1 != nil {
  260. return nil, true, err1 // abort
  261. }
  262. return nil, false, nil
  263. },
  264. func(_ int) (val interface{}, abort bool, err error) {
  265. var _remEphPub [32]byte
  266. var _, err2 = cdc.UnmarshalBinaryLengthPrefixedReader(conn, &_remEphPub, 1024*1024) // TODO
  267. if err2 != nil {
  268. return nil, true, err2 // abort
  269. }
  270. return _remEphPub, false, nil
  271. },
  272. )
  273. // If error:
  274. if trs.FirstError() != nil {
  275. err = trs.FirstError()
  276. return
  277. }
  278. // Otherwise:
  279. var _remEphPub = trs.FirstValue().([32]byte)
  280. return &_remEphPub, nil
  281. }
  282. func deriveSecrets(
  283. dhSecret *[32]byte,
  284. locIsLeast bool,
  285. ) (recvSecret, sendSecret *[aeadKeySize]byte) {
  286. hash := sha256.New
  287. hkdf := hkdf.New(hash, dhSecret[:], nil, secretConnKeyAndChallengeGen)
  288. // get enough data for 2 aead keys, and a 32 byte challenge
  289. res := new([2*aeadKeySize + 32]byte)
  290. _, err := io.ReadFull(hkdf, res[:])
  291. if err != nil {
  292. panic(err)
  293. }
  294. recvSecret = new([aeadKeySize]byte)
  295. sendSecret = new([aeadKeySize]byte)
  296. // bytes 0 through aeadKeySize - 1 are one aead key.
  297. // bytes aeadKeySize through 2*aeadKeySize -1 are another aead key.
  298. // which key corresponds to sending and receiving key depends on whether
  299. // the local key is less than the remote key.
  300. if locIsLeast {
  301. copy(recvSecret[:], res[0:aeadKeySize])
  302. copy(sendSecret[:], res[aeadKeySize:aeadKeySize*2])
  303. } else {
  304. copy(sendSecret[:], res[0:aeadKeySize])
  305. copy(recvSecret[:], res[aeadKeySize:aeadKeySize*2])
  306. }
  307. return
  308. }
  309. // computeDHSecret computes a Diffie-Hellman shared secret key
  310. // from our own local private key and the other's public key.
  311. func computeDHSecret(remPubKey, locPrivKey *[32]byte) (*[32]byte, error) {
  312. shrKey, err := curve25519.X25519(locPrivKey[:], remPubKey[:])
  313. if err != nil {
  314. return nil, err
  315. }
  316. var shrKeyArray [32]byte
  317. copy(shrKeyArray[:], shrKey)
  318. return &shrKeyArray, nil
  319. }
  320. func sort32(foo, bar *[32]byte) (lo, hi *[32]byte) {
  321. if bytes.Compare(foo[:], bar[:]) < 0 {
  322. lo = foo
  323. hi = bar
  324. } else {
  325. lo = bar
  326. hi = foo
  327. }
  328. return
  329. }
  330. func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKey) ([]byte, error) {
  331. signature, err := locPrivKey.Sign(challenge[:])
  332. if err != nil {
  333. return nil, err
  334. }
  335. return signature, nil
  336. }
  337. type authSigMessage struct {
  338. Key crypto.PubKey
  339. Sig []byte
  340. }
  341. func shareAuthSignature(sc io.ReadWriter, pubKey crypto.PubKey, signature []byte) (recvMsg authSigMessage, err error) {
  342. // Send our info and receive theirs in tandem.
  343. var trs, _ = async.Parallel(
  344. func(_ int) (val interface{}, abort bool, err error) {
  345. var _, err1 = cdc.MarshalBinaryLengthPrefixedWriter(sc, authSigMessage{pubKey, signature})
  346. if err1 != nil {
  347. return nil, true, err1 // abort
  348. }
  349. return nil, false, nil
  350. },
  351. func(_ int) (val interface{}, abort bool, err error) {
  352. var _recvMsg authSigMessage
  353. var _, err2 = cdc.UnmarshalBinaryLengthPrefixedReader(sc, &_recvMsg, 1024*1024) // TODO
  354. if err2 != nil {
  355. return nil, true, err2 // abort
  356. }
  357. return _recvMsg, false, nil
  358. },
  359. )
  360. // If error:
  361. if trs.FirstError() != nil {
  362. err = trs.FirstError()
  363. return
  364. }
  365. var _recvMsg = trs.FirstValue().(authSigMessage)
  366. return _recvMsg, nil
  367. }
  368. //--------------------------------------------------------------------------------
  369. // Increment nonce little-endian by 1 with wraparound.
  370. // Due to chacha20poly1305 expecting a 12 byte nonce we do not use the first four
  371. // bytes. We only increment a 64 bit unsigned int in the remaining 8 bytes
  372. // (little-endian in nonce[4:]).
  373. func incrNonce(nonce *[aeadNonceSize]byte) {
  374. counter := binary.LittleEndian.Uint64(nonce[4:])
  375. if counter == math.MaxUint64 {
  376. // Terminates the session and makes sure the nonce would not re-used.
  377. // See https://github.com/tendermint/tendermint/issues/3531
  378. panic("can't increase nonce without overflow")
  379. }
  380. counter++
  381. binary.LittleEndian.PutUint64(nonce[4:], counter)
  382. }