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.

475 lines
13 KiB

  1. package conn
  2. import (
  3. "bufio"
  4. "encoding/hex"
  5. "flag"
  6. "fmt"
  7. "io"
  8. "log"
  9. "net"
  10. "os"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "testing"
  16. "github.com/stretchr/testify/assert"
  17. "github.com/stretchr/testify/require"
  18. "github.com/tendermint/tendermint/crypto/ed25519"
  19. cmn "github.com/tendermint/tendermint/libs/common"
  20. )
  21. type kvstoreConn struct {
  22. *io.PipeReader
  23. *io.PipeWriter
  24. }
  25. func (drw kvstoreConn) Close() (err error) {
  26. err2 := drw.PipeWriter.CloseWithError(io.EOF)
  27. err1 := drw.PipeReader.Close()
  28. if err2 != nil {
  29. return err
  30. }
  31. return err1
  32. }
  33. // Each returned ReadWriteCloser is akin to a net.Connection
  34. func makeKVStoreConnPair() (fooConn, barConn kvstoreConn) {
  35. barReader, fooWriter := io.Pipe()
  36. fooReader, barWriter := io.Pipe()
  37. return kvstoreConn{fooReader, fooWriter}, kvstoreConn{barReader, barWriter}
  38. }
  39. func makeSecretConnPair(tb testing.TB) (fooSecConn, barSecConn *SecretConnection) {
  40. var fooConn, barConn = makeKVStoreConnPair()
  41. var fooPrvKey = ed25519.GenPrivKey()
  42. var fooPubKey = fooPrvKey.PubKey()
  43. var barPrvKey = ed25519.GenPrivKey()
  44. var barPubKey = barPrvKey.PubKey()
  45. // Make connections from both sides in parallel.
  46. var trs, ok = cmn.Parallel(
  47. func(_ int) (val interface{}, err error, abort bool) {
  48. fooSecConn, err = MakeSecretConnection(fooConn, fooPrvKey)
  49. if err != nil {
  50. tb.Errorf("Failed to establish SecretConnection for foo: %v", err)
  51. return nil, err, true
  52. }
  53. remotePubBytes := fooSecConn.RemotePubKey()
  54. if !remotePubBytes.Equals(barPubKey) {
  55. err = fmt.Errorf("Unexpected fooSecConn.RemotePubKey. Expected %v, got %v",
  56. barPubKey, fooSecConn.RemotePubKey())
  57. tb.Error(err)
  58. return nil, err, false
  59. }
  60. return nil, nil, false
  61. },
  62. func(_ int) (val interface{}, err error, abort bool) {
  63. barSecConn, err = MakeSecretConnection(barConn, barPrvKey)
  64. if barSecConn == nil {
  65. tb.Errorf("Failed to establish SecretConnection for bar: %v", err)
  66. return nil, err, true
  67. }
  68. remotePubBytes := barSecConn.RemotePubKey()
  69. if !remotePubBytes.Equals(fooPubKey) {
  70. err = fmt.Errorf("Unexpected barSecConn.RemotePubKey. Expected %v, got %v",
  71. fooPubKey, barSecConn.RemotePubKey())
  72. tb.Error(err)
  73. return nil, nil, false
  74. }
  75. return nil, nil, false
  76. },
  77. )
  78. require.Nil(tb, trs.FirstError())
  79. require.True(tb, ok, "Unexpected task abortion")
  80. return
  81. }
  82. func TestSecretConnectionHandshake(t *testing.T) {
  83. fooSecConn, barSecConn := makeSecretConnPair(t)
  84. if err := fooSecConn.Close(); err != nil {
  85. t.Error(err)
  86. }
  87. if err := barSecConn.Close(); err != nil {
  88. t.Error(err)
  89. }
  90. }
  91. // Test that shareEphPubKey rejects lower order public keys based on an
  92. // (incomplete) blacklist.
  93. func TestShareLowOrderPubkey(t *testing.T) {
  94. var fooConn, barConn = makeKVStoreConnPair()
  95. defer fooConn.Close()
  96. defer barConn.Close()
  97. locEphPub, _ := genEphKeys()
  98. // all blacklisted low order points:
  99. for _, remLowOrderPubKey := range blacklist {
  100. _, _ = cmn.Parallel(
  101. func(_ int) (val interface{}, err error, abort bool) {
  102. _, err = shareEphPubKey(fooConn, locEphPub)
  103. require.Error(t, err)
  104. require.Equal(t, err, ErrSmallOrderRemotePubKey)
  105. return nil, nil, false
  106. },
  107. func(_ int) (val interface{}, err error, abort bool) {
  108. readRemKey, err := shareEphPubKey(barConn, &remLowOrderPubKey)
  109. require.NoError(t, err)
  110. require.Equal(t, locEphPub, readRemKey)
  111. return nil, nil, false
  112. })
  113. }
  114. }
  115. // Test that additionally that the Diffie-Hellman shared secret is non-zero.
  116. // The shared secret would be zero for lower order pub-keys (but tested against the blacklist only).
  117. func TestComputeDHFailsOnLowOrder(t *testing.T) {
  118. _, locPrivKey := genEphKeys()
  119. for _, remLowOrderPubKey := range blacklist {
  120. shared, err := computeDHSecret(&remLowOrderPubKey, locPrivKey)
  121. assert.Error(t, err)
  122. assert.Equal(t, err, ErrSharedSecretIsZero)
  123. assert.Empty(t, shared)
  124. }
  125. }
  126. func TestConcurrentWrite(t *testing.T) {
  127. fooSecConn, barSecConn := makeSecretConnPair(t)
  128. fooWriteText := cmn.RandStr(dataMaxSize)
  129. // write from two routines.
  130. // should be safe from race according to net.Conn:
  131. // https://golang.org/pkg/net/#Conn
  132. n := 100
  133. wg := new(sync.WaitGroup)
  134. wg.Add(3)
  135. go writeLots(t, wg, fooSecConn, fooWriteText, n)
  136. go writeLots(t, wg, fooSecConn, fooWriteText, n)
  137. // Consume reads from bar's reader
  138. readLots(t, wg, barSecConn, n*2)
  139. wg.Wait()
  140. if err := fooSecConn.Close(); err != nil {
  141. t.Error(err)
  142. }
  143. }
  144. func TestConcurrentRead(t *testing.T) {
  145. fooSecConn, barSecConn := makeSecretConnPair(t)
  146. fooWriteText := cmn.RandStr(dataMaxSize)
  147. n := 100
  148. // read from two routines.
  149. // should be safe from race according to net.Conn:
  150. // https://golang.org/pkg/net/#Conn
  151. wg := new(sync.WaitGroup)
  152. wg.Add(3)
  153. go readLots(t, wg, fooSecConn, n/2)
  154. go readLots(t, wg, fooSecConn, n/2)
  155. // write to bar
  156. writeLots(t, wg, barSecConn, fooWriteText, n)
  157. wg.Wait()
  158. if err := fooSecConn.Close(); err != nil {
  159. t.Error(err)
  160. }
  161. }
  162. func writeLots(t *testing.T, wg *sync.WaitGroup, conn net.Conn, txt string, n int) {
  163. defer wg.Done()
  164. for i := 0; i < n; i++ {
  165. _, err := conn.Write([]byte(txt))
  166. if err != nil {
  167. t.Errorf("Failed to write to fooSecConn: %v", err)
  168. return
  169. }
  170. }
  171. }
  172. func readLots(t *testing.T, wg *sync.WaitGroup, conn net.Conn, n int) {
  173. readBuffer := make([]byte, dataMaxSize)
  174. for i := 0; i < n; i++ {
  175. _, err := conn.Read(readBuffer)
  176. assert.NoError(t, err)
  177. }
  178. wg.Done()
  179. }
  180. func TestSecretConnectionReadWrite(t *testing.T) {
  181. fooConn, barConn := makeKVStoreConnPair()
  182. fooWrites, barWrites := []string{}, []string{}
  183. fooReads, barReads := []string{}, []string{}
  184. // Pre-generate the things to write (for foo & bar)
  185. for i := 0; i < 100; i++ {
  186. fooWrites = append(fooWrites, cmn.RandStr((cmn.RandInt()%(dataMaxSize*5))+1))
  187. barWrites = append(barWrites, cmn.RandStr((cmn.RandInt()%(dataMaxSize*5))+1))
  188. }
  189. // A helper that will run with (fooConn, fooWrites, fooReads) and vice versa
  190. genNodeRunner := func(id string, nodeConn kvstoreConn, nodeWrites []string, nodeReads *[]string) cmn.Task {
  191. return func(_ int) (interface{}, error, bool) {
  192. // Initiate cryptographic private key and secret connection trhough nodeConn.
  193. nodePrvKey := ed25519.GenPrivKey()
  194. nodeSecretConn, err := MakeSecretConnection(nodeConn, nodePrvKey)
  195. if err != nil {
  196. t.Errorf("Failed to establish SecretConnection for node: %v", err)
  197. return nil, err, true
  198. }
  199. // In parallel, handle some reads and writes.
  200. var trs, ok = cmn.Parallel(
  201. func(_ int) (interface{}, error, bool) {
  202. // Node writes:
  203. for _, nodeWrite := range nodeWrites {
  204. n, err := nodeSecretConn.Write([]byte(nodeWrite))
  205. if err != nil {
  206. t.Errorf("Failed to write to nodeSecretConn: %v", err)
  207. return nil, err, true
  208. }
  209. if n != len(nodeWrite) {
  210. err = fmt.Errorf("Failed to write all bytes. Expected %v, wrote %v", len(nodeWrite), n)
  211. t.Error(err)
  212. return nil, err, true
  213. }
  214. }
  215. if err := nodeConn.PipeWriter.Close(); err != nil {
  216. t.Error(err)
  217. return nil, err, true
  218. }
  219. return nil, nil, false
  220. },
  221. func(_ int) (interface{}, error, bool) {
  222. // Node reads:
  223. readBuffer := make([]byte, dataMaxSize)
  224. for {
  225. n, err := nodeSecretConn.Read(readBuffer)
  226. if err == io.EOF {
  227. if err := nodeConn.PipeReader.Close(); err != nil {
  228. t.Error(err)
  229. return nil, err, true
  230. }
  231. return nil, nil, false
  232. } else if err != nil {
  233. t.Errorf("Failed to read from nodeSecretConn: %v", err)
  234. return nil, err, true
  235. }
  236. *nodeReads = append(*nodeReads, string(readBuffer[:n]))
  237. }
  238. },
  239. )
  240. assert.True(t, ok, "Unexpected task abortion")
  241. // If error:
  242. if trs.FirstError() != nil {
  243. return nil, trs.FirstError(), true
  244. }
  245. // Otherwise:
  246. return nil, nil, false
  247. }
  248. }
  249. // Run foo & bar in parallel
  250. var trs, ok = cmn.Parallel(
  251. genNodeRunner("foo", fooConn, fooWrites, &fooReads),
  252. genNodeRunner("bar", barConn, barWrites, &barReads),
  253. )
  254. require.Nil(t, trs.FirstError())
  255. require.True(t, ok, "unexpected task abortion")
  256. // A helper to ensure that the writes and reads match.
  257. // Additionally, small writes (<= dataMaxSize) must be atomically read.
  258. compareWritesReads := func(writes []string, reads []string) {
  259. for {
  260. // Pop next write & corresponding reads
  261. var read, write string = "", writes[0]
  262. var readCount = 0
  263. for _, readChunk := range reads {
  264. read += readChunk
  265. readCount++
  266. if len(write) <= len(read) {
  267. break
  268. }
  269. if len(write) <= dataMaxSize {
  270. break // atomicity of small writes
  271. }
  272. }
  273. // Compare
  274. if write != read {
  275. t.Errorf("Expected to read %X, got %X", write, read)
  276. }
  277. // Iterate
  278. writes = writes[1:]
  279. reads = reads[readCount:]
  280. if len(writes) == 0 {
  281. break
  282. }
  283. }
  284. }
  285. compareWritesReads(fooWrites, barReads)
  286. compareWritesReads(barWrites, fooReads)
  287. }
  288. // Run go test -update from within this module
  289. // to update the golden test vector file
  290. var update = flag.Bool("update", false, "update .golden files")
  291. func TestDeriveSecretsAndChallengeGolden(t *testing.T) {
  292. goldenFilepath := filepath.Join("testdata", t.Name()+".golden")
  293. if *update {
  294. t.Logf("Updating golden test vector file %s", goldenFilepath)
  295. data := createGoldenTestVectors(t)
  296. cmn.WriteFile(goldenFilepath, []byte(data), 0644)
  297. }
  298. f, err := os.Open(goldenFilepath)
  299. if err != nil {
  300. log.Fatal(err)
  301. }
  302. defer f.Close()
  303. scanner := bufio.NewScanner(f)
  304. for scanner.Scan() {
  305. line := scanner.Text()
  306. params := strings.Split(line, ",")
  307. randSecretVector, err := hex.DecodeString(params[0])
  308. require.Nil(t, err)
  309. randSecret := new([32]byte)
  310. copy((*randSecret)[:], randSecretVector)
  311. locIsLeast, err := strconv.ParseBool(params[1])
  312. require.Nil(t, err)
  313. expectedRecvSecret, err := hex.DecodeString(params[2])
  314. require.Nil(t, err)
  315. expectedSendSecret, err := hex.DecodeString(params[3])
  316. require.Nil(t, err)
  317. expectedChallenge, err := hex.DecodeString(params[4])
  318. require.Nil(t, err)
  319. recvSecret, sendSecret, challenge := deriveSecretAndChallenge(randSecret, locIsLeast)
  320. require.Equal(t, expectedRecvSecret, (*recvSecret)[:], "Recv Secrets aren't equal")
  321. require.Equal(t, expectedSendSecret, (*sendSecret)[:], "Send Secrets aren't equal")
  322. require.Equal(t, expectedChallenge, (*challenge)[:], "challenges aren't equal")
  323. }
  324. }
  325. // Creates the data for a test vector file.
  326. // The file format is:
  327. // Hex(diffie_hellman_secret), loc_is_least, Hex(recvSecret), Hex(sendSecret), Hex(challenge)
  328. func createGoldenTestVectors(t *testing.T) string {
  329. data := ""
  330. for i := 0; i < 32; i++ {
  331. randSecretVector := cmn.RandBytes(32)
  332. randSecret := new([32]byte)
  333. copy((*randSecret)[:], randSecretVector)
  334. data += hex.EncodeToString((*randSecret)[:]) + ","
  335. locIsLeast := cmn.RandBool()
  336. data += strconv.FormatBool(locIsLeast) + ","
  337. recvSecret, sendSecret, challenge := deriveSecretAndChallenge(randSecret, locIsLeast)
  338. data += hex.EncodeToString((*recvSecret)[:]) + ","
  339. data += hex.EncodeToString((*sendSecret)[:]) + ","
  340. data += hex.EncodeToString((*challenge)[:]) + "\n"
  341. }
  342. return data
  343. }
  344. func BenchmarkWriteSecretConnection(b *testing.B) {
  345. b.StopTimer()
  346. b.ReportAllocs()
  347. fooSecConn, barSecConn := makeSecretConnPair(b)
  348. randomMsgSizes := []int{
  349. dataMaxSize / 10,
  350. dataMaxSize / 3,
  351. dataMaxSize / 2,
  352. dataMaxSize,
  353. dataMaxSize * 3 / 2,
  354. dataMaxSize * 2,
  355. dataMaxSize * 7 / 2,
  356. }
  357. fooWriteBytes := make([][]byte, 0, len(randomMsgSizes))
  358. for _, size := range randomMsgSizes {
  359. fooWriteBytes = append(fooWriteBytes, cmn.RandBytes(size))
  360. }
  361. // Consume reads from bar's reader
  362. go func() {
  363. readBuffer := make([]byte, dataMaxSize)
  364. for {
  365. _, err := barSecConn.Read(readBuffer)
  366. if err == io.EOF {
  367. return
  368. } else if err != nil {
  369. b.Errorf("Failed to read from barSecConn: %v", err)
  370. return
  371. }
  372. }
  373. }()
  374. b.StartTimer()
  375. for i := 0; i < b.N; i++ {
  376. idx := cmn.RandIntn(len(fooWriteBytes))
  377. _, err := fooSecConn.Write(fooWriteBytes[idx])
  378. if err != nil {
  379. b.Errorf("Failed to write to fooSecConn: %v", err)
  380. return
  381. }
  382. }
  383. b.StopTimer()
  384. if err := fooSecConn.Close(); err != nil {
  385. b.Error(err)
  386. }
  387. //barSecConn.Close() race condition
  388. }
  389. func BenchmarkReadSecretConnection(b *testing.B) {
  390. b.StopTimer()
  391. b.ReportAllocs()
  392. fooSecConn, barSecConn := makeSecretConnPair(b)
  393. randomMsgSizes := []int{
  394. dataMaxSize / 10,
  395. dataMaxSize / 3,
  396. dataMaxSize / 2,
  397. dataMaxSize,
  398. dataMaxSize * 3 / 2,
  399. dataMaxSize * 2,
  400. dataMaxSize * 7 / 2,
  401. }
  402. fooWriteBytes := make([][]byte, 0, len(randomMsgSizes))
  403. for _, size := range randomMsgSizes {
  404. fooWriteBytes = append(fooWriteBytes, cmn.RandBytes(size))
  405. }
  406. go func() {
  407. for i := 0; i < b.N; i++ {
  408. idx := cmn.RandIntn(len(fooWriteBytes))
  409. _, err := fooSecConn.Write(fooWriteBytes[idx])
  410. if err != nil {
  411. b.Errorf("Failed to write to fooSecConn: %v, %v,%v", err, i, b.N)
  412. return
  413. }
  414. }
  415. }()
  416. b.StartTimer()
  417. for i := 0; i < b.N; i++ {
  418. readBuffer := make([]byte, dataMaxSize)
  419. _, err := barSecConn.Read(readBuffer)
  420. if err == io.EOF {
  421. return
  422. } else if err != nil {
  423. b.Fatalf("Failed to read from barSecConn: %v", err)
  424. }
  425. }
  426. b.StopTimer()
  427. }