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.

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