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
14 KiB

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