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.

470 lines
15 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 == nil {
  116. return nil, errors.New("Peer sent a nil public key")
  117. }
  118. if !remPubKey.VerifyBytes(challenge[:], remSignature) {
  119. return nil, errors.New("Challenge verification failed")
  120. }
  121. // We've authorized.
  122. sc.remPubKey = remPubKey
  123. return sc, nil
  124. }
  125. // RemotePubKey returns authenticated remote pubkey
  126. func (sc *SecretConnection) RemotePubKey() crypto.PubKey {
  127. return sc.remPubKey
  128. }
  129. // Writes encrypted frames of `totalFrameSize + aeadSizeOverhead`.
  130. // CONTRACT: data smaller than dataMaxSize is written atomically.
  131. func (sc *SecretConnection) Write(data []byte) (n int, err error) {
  132. sc.sendMtx.Lock()
  133. defer sc.sendMtx.Unlock()
  134. for 0 < len(data) {
  135. if err := func() error {
  136. var sealedFrame = pool.Get(aeadSizeOverhead + totalFrameSize)
  137. var frame = pool.Get(totalFrameSize)
  138. defer func() {
  139. pool.Put(sealedFrame)
  140. pool.Put(frame)
  141. }()
  142. var chunk []byte
  143. if dataMaxSize < len(data) {
  144. chunk = data[:dataMaxSize]
  145. data = data[dataMaxSize:]
  146. } else {
  147. chunk = data
  148. data = nil
  149. }
  150. chunkLength := len(chunk)
  151. binary.LittleEndian.PutUint32(frame, uint32(chunkLength))
  152. copy(frame[dataLenSize:], chunk)
  153. // encrypt the frame
  154. sc.sendAead.Seal(sealedFrame[:0], sc.sendNonce[:], frame, nil)
  155. incrNonce(sc.sendNonce)
  156. // end encryption
  157. _, err = sc.conn.Write(sealedFrame)
  158. if err != nil {
  159. return err
  160. }
  161. n += len(chunk)
  162. return nil
  163. }(); err != nil {
  164. return n, err
  165. }
  166. }
  167. return n, err
  168. }
  169. // CONTRACT: data smaller than dataMaxSize is read atomically.
  170. func (sc *SecretConnection) Read(data []byte) (n int, err error) {
  171. sc.recvMtx.Lock()
  172. defer sc.recvMtx.Unlock()
  173. // read off and update the recvBuffer, if non-empty
  174. if 0 < len(sc.recvBuffer) {
  175. n = copy(data, sc.recvBuffer)
  176. sc.recvBuffer = sc.recvBuffer[n:]
  177. return
  178. }
  179. // read off the conn
  180. var sealedFrame = pool.Get(aeadSizeOverhead + totalFrameSize)
  181. defer pool.Put(sealedFrame)
  182. _, err = io.ReadFull(sc.conn, sealedFrame)
  183. if err != nil {
  184. return
  185. }
  186. // decrypt the frame.
  187. // reads and updates the sc.recvNonce
  188. var frame = pool.Get(totalFrameSize)
  189. defer pool.Put(frame)
  190. _, err = sc.recvAead.Open(frame[:0], sc.recvNonce[:], sealedFrame, nil)
  191. if err != nil {
  192. return n, errors.New("Failed to decrypt SecretConnection")
  193. }
  194. incrNonce(sc.recvNonce)
  195. // end decryption
  196. // copy checkLength worth into data,
  197. // set recvBuffer to the rest.
  198. var chunkLength = binary.LittleEndian.Uint32(frame) // read the first four bytes
  199. if chunkLength > dataMaxSize {
  200. return 0, errors.New("chunkLength is greater than dataMaxSize")
  201. }
  202. var chunk = frame[dataLenSize : dataLenSize+chunkLength]
  203. n = copy(data, chunk)
  204. if n < len(chunk) {
  205. sc.recvBuffer = make([]byte, len(chunk)-n)
  206. copy(sc.recvBuffer, chunk[n:])
  207. }
  208. return n, err
  209. }
  210. // Implements net.Conn
  211. // nolint
  212. func (sc *SecretConnection) Close() error { return sc.conn.Close() }
  213. func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() }
  214. func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() }
  215. func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) }
  216. func (sc *SecretConnection) SetReadDeadline(t time.Time) error {
  217. return sc.conn.(net.Conn).SetReadDeadline(t)
  218. }
  219. func (sc *SecretConnection) SetWriteDeadline(t time.Time) error {
  220. return sc.conn.(net.Conn).SetWriteDeadline(t)
  221. }
  222. func genEphKeys() (ephPub, ephPriv *[32]byte) {
  223. var err error
  224. // TODO: Probably not a problem but ask Tony: different from the rust implementation (uses x25519-dalek),
  225. // we do not "clamp" the private key scalar:
  226. // see: https://github.com/dalek-cryptography/x25519-dalek/blob/34676d336049df2bba763cc076a75e47ae1f170f/src/x25519.rs#L56-L74
  227. ephPub, ephPriv, err = box.GenerateKey(crand.Reader)
  228. if err != nil {
  229. panic("Could not generate ephemeral key-pair")
  230. }
  231. return
  232. }
  233. func shareEphPubKey(conn io.ReadWriteCloser, locEphPub *[32]byte) (remEphPub *[32]byte, err error) {
  234. // Send our pubkey and receive theirs in tandem.
  235. var trs, _ = cmn.Parallel(
  236. func(_ int) (val interface{}, err error, abort bool) {
  237. var _, err1 = cdc.MarshalBinaryLengthPrefixedWriter(conn, locEphPub)
  238. if err1 != nil {
  239. return nil, err1, true // abort
  240. }
  241. return nil, nil, false
  242. },
  243. func(_ int) (val interface{}, err error, abort bool) {
  244. var _remEphPub [32]byte
  245. var _, err2 = cdc.UnmarshalBinaryLengthPrefixedReader(conn, &_remEphPub, 1024*1024) // TODO
  246. if err2 != nil {
  247. return nil, err2, true // abort
  248. }
  249. if hasSmallOrder(_remEphPub) {
  250. return nil, ErrSmallOrderRemotePubKey, true
  251. }
  252. return _remEphPub, nil, false
  253. },
  254. )
  255. // If error:
  256. if trs.FirstError() != nil {
  257. err = trs.FirstError()
  258. return
  259. }
  260. // Otherwise:
  261. var _remEphPub = trs.FirstValue().([32]byte)
  262. return &_remEphPub, nil
  263. }
  264. // use the samne blacklist as lib sodium (see https://eprint.iacr.org/2017/806.pdf for reference):
  265. // https://github.com/jedisct1/libsodium/blob/536ed00d2c5e0c65ac01e29141d69a30455f2038/src/libsodium/crypto_scalarmult/curve25519/ref10/x25519_ref10.c#L11-L17
  266. var blacklist = [][32]byte{
  267. // 0 (order 4)
  268. {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  269. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  270. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
  271. // 1 (order 1)
  272. {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  273. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  274. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
  275. // 325606250916557431795983626356110631294008115727848805560023387167927233504
  276. // (order 8)
  277. {0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae, 0x16, 0x56, 0xe3,
  278. 0xfa, 0xf1, 0x9f, 0xc4, 0x6a, 0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32,
  279. 0xb1, 0xfd, 0x86, 0x62, 0x05, 0x16, 0x5f, 0x49, 0xb8, 0x00},
  280. // 39382357235489614581723060781553021112529911719440698176882885853963445705823
  281. // (order 8)
  282. {0x5f, 0x9c, 0x95, 0xbc, 0xa3, 0x50, 0x8c, 0x24, 0xb1, 0xd0, 0xb1,
  283. 0x55, 0x9c, 0x83, 0xef, 0x5b, 0x04, 0x44, 0x5c, 0xc4, 0x58, 0x1c,
  284. 0x8e, 0x86, 0xd8, 0x22, 0x4e, 0xdd, 0xd0, 0x9f, 0x11, 0x57},
  285. // p-1 (order 2)
  286. {0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  287. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  288. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f},
  289. // p (=0, order 4)
  290. {0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  291. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  292. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f},
  293. // p+1 (=1, order 1)
  294. {0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  295. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
  296. 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f},
  297. }
  298. func hasSmallOrder(pubKey [32]byte) bool {
  299. isSmallOrderPoint := false
  300. for _, bl := range blacklist {
  301. if subtle.ConstantTimeCompare(pubKey[:], bl[:]) == 1 {
  302. isSmallOrderPoint = true
  303. break
  304. }
  305. }
  306. return isSmallOrderPoint
  307. }
  308. func deriveSecretAndChallenge(dhSecret *[32]byte, locIsLeast bool) (recvSecret, sendSecret *[aeadKeySize]byte, challenge *[32]byte) {
  309. hash := sha256.New
  310. hkdf := hkdf.New(hash, dhSecret[:], nil, []byte("TENDERMINT_SECRET_CONNECTION_KEY_AND_CHALLENGE_GEN"))
  311. // get enough data for 2 aead keys, and a 32 byte challenge
  312. res := new([2*aeadKeySize + 32]byte)
  313. _, err := io.ReadFull(hkdf, res[:])
  314. if err != nil {
  315. panic(err)
  316. }
  317. challenge = new([32]byte)
  318. recvSecret = new([aeadKeySize]byte)
  319. sendSecret = new([aeadKeySize]byte)
  320. // Use the last 32 bytes as the challenge
  321. copy(challenge[:], res[2*aeadKeySize:2*aeadKeySize+32])
  322. // bytes 0 through aeadKeySize - 1 are one aead key.
  323. // bytes aeadKeySize through 2*aeadKeySize -1 are another aead key.
  324. // which key corresponds to sending and receiving key depends on whether
  325. // the local key is less than the remote key.
  326. if locIsLeast {
  327. copy(recvSecret[:], res[0:aeadKeySize])
  328. copy(sendSecret[:], res[aeadKeySize:aeadKeySize*2])
  329. } else {
  330. copy(sendSecret[:], res[0:aeadKeySize])
  331. copy(recvSecret[:], res[aeadKeySize:aeadKeySize*2])
  332. }
  333. return
  334. }
  335. // computeDHSecret computes a Diffie-Hellman shared secret key
  336. // from our own local private key and the other's public key.
  337. //
  338. // It returns an error if the computed shared secret is all zeroes.
  339. func computeDHSecret(remPubKey, locPrivKey *[32]byte) (shrKey *[32]byte, err error) {
  340. shrKey = new([32]byte)
  341. curve25519.ScalarMult(shrKey, locPrivKey, remPubKey)
  342. // reject if the returned shared secret is all zeroes
  343. // related to: https://github.com/tendermint/tendermint/issues/3010
  344. zero := new([32]byte)
  345. if subtle.ConstantTimeCompare(shrKey[:], zero[:]) == 1 {
  346. return nil, ErrSharedSecretIsZero
  347. }
  348. return
  349. }
  350. func sort32(foo, bar *[32]byte) (lo, hi *[32]byte) {
  351. if bytes.Compare(foo[:], bar[:]) < 0 {
  352. lo = foo
  353. hi = bar
  354. } else {
  355. lo = bar
  356. hi = foo
  357. }
  358. return
  359. }
  360. func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKey) (signature []byte) {
  361. signature, err := locPrivKey.Sign(challenge[:])
  362. // TODO(ismail): let signChallenge return an error instead
  363. if err != nil {
  364. panic(err)
  365. }
  366. return
  367. }
  368. type authSigMessage struct {
  369. Key crypto.PubKey
  370. Sig []byte
  371. }
  372. func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKey, signature []byte) (recvMsg authSigMessage, err error) {
  373. // Send our info and receive theirs in tandem.
  374. var trs, _ = cmn.Parallel(
  375. func(_ int) (val interface{}, err error, abort bool) {
  376. var _, err1 = cdc.MarshalBinaryLengthPrefixedWriter(sc, authSigMessage{pubKey, signature})
  377. if err1 != nil {
  378. return nil, err1, true // abort
  379. }
  380. return nil, nil, false
  381. },
  382. func(_ int) (val interface{}, err error, abort bool) {
  383. var _recvMsg authSigMessage
  384. var _, err2 = cdc.UnmarshalBinaryLengthPrefixedReader(sc, &_recvMsg, 1024*1024) // TODO
  385. if err2 != nil {
  386. return nil, err2, true // abort
  387. }
  388. return _recvMsg, nil, false
  389. },
  390. )
  391. // If error:
  392. if trs.FirstError() != nil {
  393. err = trs.FirstError()
  394. return
  395. }
  396. var _recvMsg = trs.FirstValue().(authSigMessage)
  397. return _recvMsg, nil
  398. }
  399. //--------------------------------------------------------------------------------
  400. // Increment nonce little-endian by 1 with wraparound.
  401. // Due to chacha20poly1305 expecting a 12 byte nonce we do not use the first four
  402. // bytes. We only increment a 64 bit unsigned int in the remaining 8 bytes
  403. // (little-endian in nonce[4:]).
  404. func incrNonce(nonce *[aeadNonceSize]byte) {
  405. counter := binary.LittleEndian.Uint64(nonce[4:])
  406. if counter == math.MaxUint64 {
  407. // Terminates the session and makes sure the nonce would not re-used.
  408. // See https://github.com/tendermint/tendermint/issues/3531
  409. panic("can't increase nonce without overflow")
  410. }
  411. counter++
  412. binary.LittleEndian.PutUint64(nonce[4:], counter)
  413. }