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.

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