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.

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