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.

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