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.

424 lines
13 KiB

  1. package conn
  2. import (
  3. "bytes"
  4. crand "crypto/rand"
  5. "crypto/sha256"
  6. "crypto/subtle"
  7. "encoding/binary"
  8. "errors"
  9. "io"
  10. "net"
  11. "sync"
  12. "time"
  13. "golang.org/x/crypto/chacha20poly1305"
  14. "golang.org/x/crypto/curve25519"
  15. "golang.org/x/crypto/nacl/box"
  16. "github.com/tendermint/tendermint/crypto"
  17. cmn "github.com/tendermint/tendermint/libs/common"
  18. "golang.org/x/crypto/hkdf"
  19. )
  20. // 4 + 1024 == 1028 total frame size
  21. const dataLenSize = 4
  22. const dataMaxSize = 1024
  23. const totalFrameSize = dataMaxSize + dataLenSize
  24. const aeadSizeOverhead = 16 // overhead of poly 1305 authentication tag
  25. const aeadKeySize = chacha20poly1305.KeySize
  26. const aeadNonceSize = chacha20poly1305.NonceSize
  27. var ErrSmallOrderRemotePubKey = errors.New("detected low order point from remote peer")
  28. // SecretConnection implements net.Conn.
  29. // It is an implementation of the STS protocol.
  30. // See https://github.com/tendermint/tendermint/blob/0.1/docs/sts-final.pdf for
  31. // details on the protocol.
  32. //
  33. // Consumers of the SecretConnection are responsible for authenticating
  34. // the remote peer's pubkey against known information, like a nodeID.
  35. // Otherwise they are vulnerable to MITM.
  36. // (TODO(ismail): see also https://github.com/tendermint/tendermint/issues/3010)
  37. type SecretConnection struct {
  38. // immutable
  39. recvSecret *[aeadKeySize]byte
  40. sendSecret *[aeadKeySize]byte
  41. remPubKey crypto.PubKey
  42. conn io.ReadWriteCloser
  43. // net.Conn must be thread safe:
  44. // https://golang.org/pkg/net/#Conn.
  45. // Since we have internal mutable state,
  46. // we need mtxs. But recv and send states
  47. // are independent, so we can use two mtxs.
  48. // All .Read are covered by recvMtx,
  49. // all .Write are covered by sendMtx.
  50. recvMtx sync.Mutex
  51. recvBuffer []byte
  52. recvNonce *[aeadNonceSize]byte
  53. sendMtx sync.Mutex
  54. sendNonce *[aeadNonceSize]byte
  55. }
  56. // MakeSecretConnection performs handshake and returns a new authenticated
  57. // SecretConnection.
  58. // Returns nil if there is an error in handshake.
  59. // Caller should call conn.Close()
  60. // See docs/sts-final.pdf for more information.
  61. func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKey) (*SecretConnection, error) {
  62. locPubKey := locPrivKey.PubKey()
  63. // Generate ephemeral keys for perfect forward secrecy.
  64. locEphPub, locEphPriv := genEphKeys()
  65. // Write local ephemeral pubkey and receive one too.
  66. // NOTE: every 32-byte string is accepted as a Curve25519 public key
  67. // (see DJB's Curve25519 paper: http://cr.yp.to/ecdh/curve25519-20060209.pdf)
  68. remEphPub, err := shareEphPubKey(conn, locEphPub)
  69. if err != nil {
  70. return nil, err
  71. }
  72. // Sort by lexical order.
  73. loEphPub, _ := sort32(locEphPub, remEphPub)
  74. // Check if the local ephemeral public key
  75. // was the least, lexicographically sorted.
  76. locIsLeast := bytes.Equal(locEphPub[:], loEphPub[:])
  77. // Compute common diffie hellman secret using X25519.
  78. dhSecret := computeDHSecret(remEphPub, locEphPriv)
  79. // generate the secret used for receiving, sending, challenge via hkdf-sha2 on dhSecret
  80. recvSecret, sendSecret, challenge := deriveSecretAndChallenge(dhSecret, locIsLeast)
  81. // Construct SecretConnection.
  82. sc := &SecretConnection{
  83. conn: conn,
  84. recvBuffer: nil,
  85. recvNonce: new([aeadNonceSize]byte),
  86. sendNonce: new([aeadNonceSize]byte),
  87. recvSecret: recvSecret,
  88. sendSecret: sendSecret,
  89. }
  90. // Sign the challenge bytes for authentication.
  91. locSignature := signChallenge(challenge, locPrivKey)
  92. // Share (in secret) each other's pubkey & challenge signature
  93. authSigMsg, err := shareAuthSignature(sc, locPubKey, locSignature)
  94. if err != nil {
  95. return nil, err
  96. }
  97. remPubKey, remSignature := authSigMsg.Key, authSigMsg.Sig
  98. if !remPubKey.VerifyBytes(challenge[:], remSignature) {
  99. return nil, errors.New("Challenge verification failed")
  100. }
  101. // We've authorized.
  102. sc.remPubKey = remPubKey
  103. return sc, nil
  104. }
  105. // RemotePubKey returns authenticated remote pubkey
  106. func (sc *SecretConnection) RemotePubKey() crypto.PubKey {
  107. return sc.remPubKey
  108. }
  109. // Writes encrypted frames of `totalFrameSize + aeadSizeOverhead`.
  110. // CONTRACT: data smaller than dataMaxSize is written atomically.
  111. func (sc *SecretConnection) Write(data []byte) (n int, err error) {
  112. sc.sendMtx.Lock()
  113. defer sc.sendMtx.Unlock()
  114. for 0 < len(data) {
  115. var frame = make([]byte, totalFrameSize)
  116. var chunk []byte
  117. if dataMaxSize < len(data) {
  118. chunk = data[:dataMaxSize]
  119. data = data[dataMaxSize:]
  120. } else {
  121. chunk = data
  122. data = nil
  123. }
  124. chunkLength := len(chunk)
  125. binary.LittleEndian.PutUint32(frame, uint32(chunkLength))
  126. copy(frame[dataLenSize:], chunk)
  127. aead, err := chacha20poly1305.New(sc.sendSecret[:])
  128. if err != nil {
  129. return n, errors.New("Invalid SecretConnection Key")
  130. }
  131. // encrypt the frame
  132. var sealedFrame = make([]byte, aeadSizeOverhead+totalFrameSize)
  133. aead.Seal(sealedFrame[:0], sc.sendNonce[:], frame, nil)
  134. incrNonce(sc.sendNonce)
  135. // end encryption
  136. _, err = sc.conn.Write(sealedFrame)
  137. if err != nil {
  138. return n, err
  139. }
  140. n += len(chunk)
  141. }
  142. return
  143. }
  144. // CONTRACT: data smaller than dataMaxSize is read atomically.
  145. func (sc *SecretConnection) Read(data []byte) (n int, err error) {
  146. sc.recvMtx.Lock()
  147. defer sc.recvMtx.Unlock()
  148. // read off and update the recvBuffer, if non-empty
  149. if 0 < len(sc.recvBuffer) {
  150. n = copy(data, sc.recvBuffer)
  151. sc.recvBuffer = sc.recvBuffer[n:]
  152. return
  153. }
  154. // read off the conn
  155. sealedFrame := make([]byte, totalFrameSize+aeadSizeOverhead)
  156. _, err = io.ReadFull(sc.conn, sealedFrame)
  157. if err != nil {
  158. return
  159. }
  160. aead, err := chacha20poly1305.New(sc.recvSecret[:])
  161. if err != nil {
  162. return n, errors.New("Invalid SecretConnection Key")
  163. }
  164. // decrypt the frame.
  165. // reads and updates the sc.recvNonce
  166. var frame = make([]byte, totalFrameSize)
  167. _, err = aead.Open(frame[:0], sc.recvNonce[:], sealedFrame, nil)
  168. if err != nil {
  169. return n, errors.New("Failed to decrypt SecretConnection")
  170. }
  171. incrNonce(sc.recvNonce)
  172. // end decryption
  173. // copy checkLength worth into data,
  174. // set recvBuffer to the rest.
  175. var chunkLength = binary.LittleEndian.Uint32(frame) // read the first four bytes
  176. if chunkLength > dataMaxSize {
  177. return 0, errors.New("chunkLength is greater than dataMaxSize")
  178. }
  179. var chunk = frame[dataLenSize : dataLenSize+chunkLength]
  180. n = copy(data, chunk)
  181. sc.recvBuffer = chunk[n:]
  182. return
  183. }
  184. // Implements net.Conn
  185. // nolint
  186. func (sc *SecretConnection) Close() error { return sc.conn.Close() }
  187. func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() }
  188. func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() }
  189. func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) }
  190. func (sc *SecretConnection) SetReadDeadline(t time.Time) error {
  191. return sc.conn.(net.Conn).SetReadDeadline(t)
  192. }
  193. func (sc *SecretConnection) SetWriteDeadline(t time.Time) error {
  194. return sc.conn.(net.Conn).SetWriteDeadline(t)
  195. }
  196. func genEphKeys() (ephPub, ephPriv *[32]byte) {
  197. var err error
  198. ephPub, ephPriv, err = box.GenerateKey(crand.Reader)
  199. if err != nil {
  200. panic("Could not generate ephemeral keypairs")
  201. }
  202. return
  203. }
  204. func shareEphPubKey(conn io.ReadWriteCloser, locEphPub *[32]byte) (remEphPub *[32]byte, err error) {
  205. // Send our pubkey and receive theirs in tandem.
  206. var trs, _ = cmn.Parallel(
  207. func(_ int) (val interface{}, err error, abort bool) {
  208. var _, err1 = cdc.MarshalBinaryLengthPrefixedWriter(conn, locEphPub)
  209. if err1 != nil {
  210. return nil, err1, true // abort
  211. }
  212. return nil, nil, false
  213. },
  214. func(_ int) (val interface{}, err error, abort bool) {
  215. var _remEphPub [32]byte
  216. var _, err2 = cdc.UnmarshalBinaryLengthPrefixedReader(conn, &_remEphPub, 1024*1024) // TODO
  217. if err2 != nil {
  218. return nil, err2, true // abort
  219. }
  220. if hasSmallOrder(_remEphPub) {
  221. return nil, ErrSmallOrderRemotePubKey, true
  222. }
  223. return _remEphPub, nil, false
  224. },
  225. )
  226. // If error:
  227. if trs.FirstError() != nil {
  228. err = trs.FirstError()
  229. return
  230. }
  231. // Otherwise:
  232. var _remEphPub = trs.FirstValue().([32]byte)
  233. return &_remEphPub, nil
  234. }
  235. // use the samne blacklist as lib sodium (see https://eprint.iacr.org/2017/806.pdf for reference):
  236. // https://github.com/jedisct1/libsodium/blob/536ed00d2c5e0c65ac01e29141d69a30455f2038/src/libsodium/crypto_scalarmult/curve25519/ref10/x25519_ref10.c#L11-L17
  237. var blacklist = [][32]byte{
  238. // 0 (order 4)
  239. {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  240. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  241. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
  242. // 1 (order 1)
  243. {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  244. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  245. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
  246. // 325606250916557431795983626356110631294008115727848805560023387167927233504
  247. // (order 8)
  248. {0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae, 0x16, 0x56, 0xe3,
  249. 0xfa, 0xf1, 0x9f, 0xc4, 0x6a, 0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32,
  250. 0xb1, 0xfd, 0x86, 0x62, 0x05, 0x16, 0x5f, 0x49, 0xb8, 0x00},
  251. // 39382357235489614581723060781553021112529911719440698176882885853963445705823
  252. // (order 8)
  253. {0x5f, 0x9c, 0x95, 0xbc, 0xa3, 0x50, 0x8c, 0x24, 0xb1, 0xd0, 0xb1,
  254. 0x55, 0x9c, 0x83, 0xef, 0x5b, 0x04, 0x44, 0x5c, 0xc4, 0x58, 0x1c,
  255. 0x8e, 0x86, 0xd8, 0x22, 0x4e, 0xdd, 0xd0, 0x9f, 0x11, 0x57},
  256. // p-1 (order 2)
  257. {0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  258. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  259. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f},
  260. // p (=0, order 4)
  261. {0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  262. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  263. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f},
  264. // p+1 (=1, order 1)
  265. {0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  266. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  267. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f},
  268. }
  269. func hasSmallOrder(pubKey [32]byte) bool {
  270. isSmallOrderPoint := false
  271. for _, bl := range blacklist {
  272. if subtle.ConstantTimeCompare(pubKey[:], bl[:]) == 1 {
  273. isSmallOrderPoint = true
  274. break
  275. }
  276. }
  277. return isSmallOrderPoint
  278. }
  279. func deriveSecretAndChallenge(dhSecret *[32]byte, locIsLeast bool) (recvSecret, sendSecret *[aeadKeySize]byte, challenge *[32]byte) {
  280. hash := sha256.New
  281. hkdf := hkdf.New(hash, dhSecret[:], nil, []byte("TENDERMINT_SECRET_CONNECTION_KEY_AND_CHALLENGE_GEN"))
  282. // get enough data for 2 aead keys, and a 32 byte challenge
  283. res := new([2*aeadKeySize + 32]byte)
  284. _, err := io.ReadFull(hkdf, res[:])
  285. if err != nil {
  286. panic(err)
  287. }
  288. challenge = new([32]byte)
  289. recvSecret = new([aeadKeySize]byte)
  290. sendSecret = new([aeadKeySize]byte)
  291. // Use the last 32 bytes as the challenge
  292. copy(challenge[:], res[2*aeadKeySize:2*aeadKeySize+32])
  293. // bytes 0 through aeadKeySize - 1 are one aead key.
  294. // bytes aeadKeySize through 2*aeadKeySize -1 are another aead key.
  295. // which key corresponds to sending and receiving key depends on whether
  296. // the local key is less than the remote key.
  297. if locIsLeast {
  298. copy(recvSecret[:], res[0:aeadKeySize])
  299. copy(sendSecret[:], res[aeadKeySize:aeadKeySize*2])
  300. } else {
  301. copy(sendSecret[:], res[0:aeadKeySize])
  302. copy(recvSecret[:], res[aeadKeySize:aeadKeySize*2])
  303. }
  304. return
  305. }
  306. func computeDHSecret(remPubKey, locPrivKey *[32]byte) (shrKey *[32]byte) {
  307. shrKey = new([32]byte)
  308. curve25519.ScalarMult(shrKey, locPrivKey, remPubKey)
  309. return
  310. }
  311. func sort32(foo, bar *[32]byte) (lo, hi *[32]byte) {
  312. if bytes.Compare(foo[:], bar[:]) < 0 {
  313. lo = foo
  314. hi = bar
  315. } else {
  316. lo = bar
  317. hi = foo
  318. }
  319. return
  320. }
  321. func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKey) (signature []byte) {
  322. signature, err := locPrivKey.Sign(challenge[:])
  323. // TODO(ismail): let signChallenge return an error instead
  324. if err != nil {
  325. panic(err)
  326. }
  327. return
  328. }
  329. type authSigMessage struct {
  330. Key crypto.PubKey
  331. Sig []byte
  332. }
  333. func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKey, signature []byte) (recvMsg authSigMessage, err error) {
  334. // Send our info and receive theirs in tandem.
  335. var trs, _ = cmn.Parallel(
  336. func(_ int) (val interface{}, err error, abort bool) {
  337. var _, err1 = cdc.MarshalBinaryLengthPrefixedWriter(sc, authSigMessage{pubKey, signature})
  338. if err1 != nil {
  339. return nil, err1, true // abort
  340. }
  341. return nil, nil, false
  342. },
  343. func(_ int) (val interface{}, err error, abort bool) {
  344. var _recvMsg authSigMessage
  345. var _, err2 = cdc.UnmarshalBinaryLengthPrefixedReader(sc, &_recvMsg, 1024*1024) // TODO
  346. if err2 != nil {
  347. return nil, err2, true // abort
  348. }
  349. return _recvMsg, nil, false
  350. },
  351. )
  352. // If error:
  353. if trs.FirstError() != nil {
  354. err = trs.FirstError()
  355. return
  356. }
  357. var _recvMsg = trs.FirstValue().(authSigMessage)
  358. return _recvMsg, nil
  359. }
  360. //--------------------------------------------------------------------------------
  361. // Increment nonce little-endian by 1 with wraparound.
  362. // Due to chacha20poly1305 expecting a 12 byte nonce we do not use the first four
  363. // bytes. We only increment a 64 bit unsigned int in the remaining 8 bytes
  364. // (little-endian in nonce[4:]).
  365. func incrNonce(nonce *[aeadNonceSize]byte) {
  366. counter := binary.LittleEndian.Uint64(nonce[4:])
  367. counter++
  368. binary.LittleEndian.PutUint64(nonce[4:], counter)
  369. }