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.

466 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. "time"
  14. gogotypes "github.com/gogo/protobuf/types"
  15. "github.com/gtank/merlin"
  16. pool "github.com/libp2p/go-buffer-pool"
  17. "golang.org/x/crypto/chacha20poly1305"
  18. "golang.org/x/crypto/curve25519"
  19. "golang.org/x/crypto/hkdf"
  20. "golang.org/x/crypto/nacl/box"
  21. "github.com/tendermint/tendermint/crypto"
  22. "github.com/tendermint/tendermint/crypto/ed25519"
  23. cryptoenc "github.com/tendermint/tendermint/crypto/encoding"
  24. "github.com/tendermint/tendermint/libs/async"
  25. "github.com/tendermint/tendermint/libs/protoio"
  26. tmsync "github.com/tendermint/tendermint/libs/sync"
  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 tmsync.Mutex
  69. recvBuffer []byte
  70. recvNonce *[aeadNonceSize]byte
  71. sendMtx tmsync.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.VerifySignature(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. func (sc *SecretConnection) Close() error { return sc.conn.Close() }
  238. func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() }
  239. func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() }
  240. func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) }
  241. func (sc *SecretConnection) SetReadDeadline(t time.Time) error {
  242. return sc.conn.(net.Conn).SetReadDeadline(t)
  243. }
  244. func (sc *SecretConnection) SetWriteDeadline(t time.Time) error {
  245. return sc.conn.(net.Conn).SetWriteDeadline(t)
  246. }
  247. func genEphKeys() (ephPub, ephPriv *[32]byte) {
  248. var err error
  249. // TODO: Probably not a problem but ask Tony: different from the rust implementation (uses x25519-dalek),
  250. // we do not "clamp" the private key scalar:
  251. // see: https://github.com/dalek-cryptography/x25519-dalek/blob/34676d336049df2bba763cc076a75e47ae1f170f/src/x25519.rs#L56-L74
  252. ephPub, ephPriv, err = box.GenerateKey(crand.Reader)
  253. if err != nil {
  254. panic("Could not generate ephemeral key-pair")
  255. }
  256. return
  257. }
  258. func shareEphPubKey(conn io.ReadWriter, locEphPub *[32]byte) (remEphPub *[32]byte, err error) {
  259. // Send our pubkey and receive theirs in tandem.
  260. var trs, _ = async.Parallel(
  261. func(_ int) (val interface{}, abort bool, err error) {
  262. lc := *locEphPub
  263. _, err = protoio.NewDelimitedWriter(conn).WriteMsg(&gogotypes.BytesValue{Value: lc[:]})
  264. if err != nil {
  265. return nil, true, err // abort
  266. }
  267. return nil, false, nil
  268. },
  269. func(_ int) (val interface{}, abort bool, err error) {
  270. var bytes gogotypes.BytesValue
  271. _, err = protoio.NewDelimitedReader(conn, 1024*1024).ReadMsg(&bytes)
  272. if err != nil {
  273. return nil, true, err // abort
  274. }
  275. var _remEphPub [32]byte
  276. copy(_remEphPub[:], bytes.Value)
  277. return _remEphPub, false, nil
  278. },
  279. )
  280. // If error:
  281. if trs.FirstError() != nil {
  282. err = trs.FirstError()
  283. return
  284. }
  285. // Otherwise:
  286. var _remEphPub = trs.FirstValue().([32]byte)
  287. return &_remEphPub, nil
  288. }
  289. func deriveSecrets(
  290. dhSecret *[32]byte,
  291. locIsLeast bool,
  292. ) (recvSecret, sendSecret *[aeadKeySize]byte) {
  293. hash := sha256.New
  294. hkdf := hkdf.New(hash, dhSecret[:], nil, secretConnKeyAndChallengeGen)
  295. // get enough data for 2 aead keys, and a 32 byte challenge
  296. res := new([2*aeadKeySize + 32]byte)
  297. _, err := io.ReadFull(hkdf, res[:])
  298. if err != nil {
  299. panic(err)
  300. }
  301. recvSecret = new([aeadKeySize]byte)
  302. sendSecret = new([aeadKeySize]byte)
  303. // bytes 0 through aeadKeySize - 1 are one aead key.
  304. // bytes aeadKeySize through 2*aeadKeySize -1 are another aead key.
  305. // which key corresponds to sending and receiving key depends on whether
  306. // the local key is less than the remote key.
  307. if locIsLeast {
  308. copy(recvSecret[:], res[0:aeadKeySize])
  309. copy(sendSecret[:], res[aeadKeySize:aeadKeySize*2])
  310. } else {
  311. copy(sendSecret[:], res[0:aeadKeySize])
  312. copy(recvSecret[:], res[aeadKeySize:aeadKeySize*2])
  313. }
  314. return
  315. }
  316. // computeDHSecret computes a Diffie-Hellman shared secret key
  317. // from our own local private key and the other's public key.
  318. func computeDHSecret(remPubKey, locPrivKey *[32]byte) (*[32]byte, error) {
  319. shrKey, err := curve25519.X25519(locPrivKey[:], remPubKey[:])
  320. if err != nil {
  321. return nil, err
  322. }
  323. var shrKeyArray [32]byte
  324. copy(shrKeyArray[:], shrKey)
  325. return &shrKeyArray, nil
  326. }
  327. func sort32(foo, bar *[32]byte) (lo, hi *[32]byte) {
  328. if bytes.Compare(foo[:], bar[:]) < 0 {
  329. lo = foo
  330. hi = bar
  331. } else {
  332. lo = bar
  333. hi = foo
  334. }
  335. return
  336. }
  337. func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKey) ([]byte, error) {
  338. signature, err := locPrivKey.Sign(challenge[:])
  339. if err != nil {
  340. return nil, err
  341. }
  342. return signature, nil
  343. }
  344. type authSigMessage struct {
  345. Key crypto.PubKey
  346. Sig []byte
  347. }
  348. func shareAuthSignature(sc io.ReadWriter, pubKey crypto.PubKey, signature []byte) (recvMsg authSigMessage, err error) {
  349. // Send our info and receive theirs in tandem.
  350. var trs, _ = async.Parallel(
  351. func(_ int) (val interface{}, abort bool, err error) {
  352. pbpk, err := cryptoenc.PubKeyToProto(pubKey)
  353. if err != nil {
  354. return nil, true, err
  355. }
  356. _, err = protoio.NewDelimitedWriter(sc).WriteMsg(&tmp2p.AuthSigMessage{PubKey: pbpk, Sig: signature})
  357. if err != nil {
  358. return nil, true, err // abort
  359. }
  360. return nil, false, nil
  361. },
  362. func(_ int) (val interface{}, abort bool, err error) {
  363. var pba tmp2p.AuthSigMessage
  364. _, err = protoio.NewDelimitedReader(sc, 1024*1024).ReadMsg(&pba)
  365. if err != nil {
  366. return nil, true, err // abort
  367. }
  368. pk, err := cryptoenc.PubKeyFromProto(pba.PubKey)
  369. if err != nil {
  370. return nil, true, err // abort
  371. }
  372. _recvMsg := authSigMessage{
  373. Key: pk,
  374. Sig: pba.Sig,
  375. }
  376. return _recvMsg, false, nil
  377. },
  378. )
  379. // If error:
  380. if trs.FirstError() != nil {
  381. err = trs.FirstError()
  382. return
  383. }
  384. var _recvMsg = trs.FirstValue().(authSigMessage)
  385. return _recvMsg, nil
  386. }
  387. //--------------------------------------------------------------------------------
  388. // Increment nonce little-endian by 1 with wraparound.
  389. // Due to chacha20poly1305 expecting a 12 byte nonce we do not use the first four
  390. // bytes. We only increment a 64 bit unsigned int in the remaining 8 bytes
  391. // (little-endian in nonce[4:]).
  392. func incrNonce(nonce *[aeadNonceSize]byte) {
  393. counter := binary.LittleEndian.Uint64(nonce[4:])
  394. if counter == math.MaxUint64 {
  395. // Terminates the session and makes sure the nonce would not re-used.
  396. // See https://github.com/tendermint/tendermint/issues/3531
  397. panic("can't increase nonce without overflow")
  398. }
  399. counter++
  400. binary.LittleEndian.PutUint64(nonce[4:], counter)
  401. }