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.

456 lines
14 KiB

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