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.

471 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.Fatalf("Failed to write to fooSecConn: %v", err)
  168. }
  169. }
  170. }
  171. func readLots(t *testing.T, wg *sync.WaitGroup, conn net.Conn, n int) {
  172. readBuffer := make([]byte, dataMaxSize)
  173. for i := 0; i < n; i++ {
  174. _, err := conn.Read(readBuffer)
  175. assert.NoError(t, err)
  176. }
  177. wg.Done()
  178. }
  179. func TestSecretConnectionReadWrite(t *testing.T) {
  180. fooConn, barConn := makeKVStoreConnPair()
  181. fooWrites, barWrites := []string{}, []string{}
  182. fooReads, barReads := []string{}, []string{}
  183. // Pre-generate the things to write (for foo & bar)
  184. for i := 0; i < 100; i++ {
  185. fooWrites = append(fooWrites, cmn.RandStr((cmn.RandInt()%(dataMaxSize*5))+1))
  186. barWrites = append(barWrites, cmn.RandStr((cmn.RandInt()%(dataMaxSize*5))+1))
  187. }
  188. // A helper that will run with (fooConn, fooWrites, fooReads) and vice versa
  189. genNodeRunner := func(id string, nodeConn kvstoreConn, nodeWrites []string, nodeReads *[]string) cmn.Task {
  190. return func(_ int) (interface{}, error, bool) {
  191. // Initiate cryptographic private key and secret connection trhough nodeConn.
  192. nodePrvKey := ed25519.GenPrivKey()
  193. nodeSecretConn, err := MakeSecretConnection(nodeConn, nodePrvKey)
  194. if err != nil {
  195. t.Errorf("Failed to establish SecretConnection for node: %v", err)
  196. return nil, err, true
  197. }
  198. // In parallel, handle some reads and writes.
  199. var trs, ok = cmn.Parallel(
  200. func(_ int) (interface{}, error, bool) {
  201. // Node writes:
  202. for _, nodeWrite := range nodeWrites {
  203. n, err := nodeSecretConn.Write([]byte(nodeWrite))
  204. if err != nil {
  205. t.Errorf("Failed to write to nodeSecretConn: %v", err)
  206. return nil, err, true
  207. }
  208. if n != len(nodeWrite) {
  209. err = fmt.Errorf("Failed to write all bytes. Expected %v, wrote %v", len(nodeWrite), n)
  210. t.Error(err)
  211. return nil, err, true
  212. }
  213. }
  214. if err := nodeConn.PipeWriter.Close(); err != nil {
  215. t.Error(err)
  216. return nil, err, true
  217. }
  218. return nil, nil, false
  219. },
  220. func(_ int) (interface{}, error, bool) {
  221. // Node reads:
  222. readBuffer := make([]byte, dataMaxSize)
  223. for {
  224. n, err := nodeSecretConn.Read(readBuffer)
  225. if err == io.EOF {
  226. if err := nodeConn.PipeReader.Close(); err != nil {
  227. t.Error(err)
  228. return nil, err, true
  229. }
  230. return nil, nil, false
  231. } else if err != nil {
  232. t.Errorf("Failed to read from nodeSecretConn: %v", err)
  233. return nil, err, true
  234. }
  235. *nodeReads = append(*nodeReads, string(readBuffer[:n]))
  236. }
  237. },
  238. )
  239. assert.True(t, ok, "Unexpected task abortion")
  240. // If error:
  241. if trs.FirstError() != nil {
  242. return nil, trs.FirstError(), true
  243. }
  244. // Otherwise:
  245. return nil, nil, false
  246. }
  247. }
  248. // Run foo & bar in parallel
  249. var trs, ok = cmn.Parallel(
  250. genNodeRunner("foo", fooConn, fooWrites, &fooReads),
  251. genNodeRunner("bar", barConn, barWrites, &barReads),
  252. )
  253. require.Nil(t, trs.FirstError())
  254. require.True(t, ok, "unexpected task abortion")
  255. // A helper to ensure that the writes and reads match.
  256. // Additionally, small writes (<= dataMaxSize) must be atomically read.
  257. compareWritesReads := func(writes []string, reads []string) {
  258. for {
  259. // Pop next write & corresponding reads
  260. var read, write string = "", writes[0]
  261. var readCount = 0
  262. for _, readChunk := range reads {
  263. read += readChunk
  264. readCount++
  265. if len(write) <= len(read) {
  266. break
  267. }
  268. if len(write) <= dataMaxSize {
  269. break // atomicity of small writes
  270. }
  271. }
  272. // Compare
  273. if write != read {
  274. t.Errorf("Expected to read %X, got %X", write, read)
  275. }
  276. // Iterate
  277. writes = writes[1:]
  278. reads = reads[readCount:]
  279. if len(writes) == 0 {
  280. break
  281. }
  282. }
  283. }
  284. compareWritesReads(fooWrites, barReads)
  285. compareWritesReads(barWrites, fooReads)
  286. }
  287. // Run go test -update from within this module
  288. // to update the golden test vector file
  289. var update = flag.Bool("update", false, "update .golden files")
  290. func TestDeriveSecretsAndChallengeGolden(t *testing.T) {
  291. goldenFilepath := filepath.Join("testdata", t.Name()+".golden")
  292. if *update {
  293. t.Logf("Updating golden test vector file %s", goldenFilepath)
  294. data := createGoldenTestVectors(t)
  295. cmn.WriteFile(goldenFilepath, []byte(data), 0644)
  296. }
  297. f, err := os.Open(goldenFilepath)
  298. if err != nil {
  299. log.Fatal(err)
  300. }
  301. defer f.Close()
  302. scanner := bufio.NewScanner(f)
  303. for scanner.Scan() {
  304. line := scanner.Text()
  305. params := strings.Split(line, ",")
  306. randSecretVector, err := hex.DecodeString(params[0])
  307. require.Nil(t, err)
  308. randSecret := new([32]byte)
  309. copy((*randSecret)[:], randSecretVector)
  310. locIsLeast, err := strconv.ParseBool(params[1])
  311. require.Nil(t, err)
  312. expectedRecvSecret, err := hex.DecodeString(params[2])
  313. require.Nil(t, err)
  314. expectedSendSecret, err := hex.DecodeString(params[3])
  315. require.Nil(t, err)
  316. expectedChallenge, err := hex.DecodeString(params[4])
  317. require.Nil(t, err)
  318. recvSecret, sendSecret, challenge := deriveSecretAndChallenge(randSecret, locIsLeast)
  319. require.Equal(t, expectedRecvSecret, (*recvSecret)[:], "Recv Secrets aren't equal")
  320. require.Equal(t, expectedSendSecret, (*sendSecret)[:], "Send Secrets aren't equal")
  321. require.Equal(t, expectedChallenge, (*challenge)[:], "challenges aren't equal")
  322. }
  323. }
  324. // Creates the data for a test vector file.
  325. // The file format is:
  326. // Hex(diffie_hellman_secret), loc_is_least, Hex(recvSecret), Hex(sendSecret), Hex(challenge)
  327. func createGoldenTestVectors(t *testing.T) string {
  328. data := ""
  329. for i := 0; i < 32; i++ {
  330. randSecretVector := cmn.RandBytes(32)
  331. randSecret := new([32]byte)
  332. copy((*randSecret)[:], randSecretVector)
  333. data += hex.EncodeToString((*randSecret)[:]) + ","
  334. locIsLeast := cmn.RandBool()
  335. data += strconv.FormatBool(locIsLeast) + ","
  336. recvSecret, sendSecret, challenge := deriveSecretAndChallenge(randSecret, locIsLeast)
  337. data += hex.EncodeToString((*recvSecret)[:]) + ","
  338. data += hex.EncodeToString((*sendSecret)[:]) + ","
  339. data += hex.EncodeToString((*challenge)[:]) + "\n"
  340. }
  341. return data
  342. }
  343. func BenchmarkWriteSecretConnection(b *testing.B) {
  344. b.StopTimer()
  345. b.ReportAllocs()
  346. fooSecConn, barSecConn := makeSecretConnPair(b)
  347. randomMsgSizes := []int{
  348. dataMaxSize / 10,
  349. dataMaxSize / 3,
  350. dataMaxSize / 2,
  351. dataMaxSize,
  352. dataMaxSize * 3 / 2,
  353. dataMaxSize * 2,
  354. dataMaxSize * 7 / 2,
  355. }
  356. fooWriteBytes := make([][]byte, 0, len(randomMsgSizes))
  357. for _, size := range randomMsgSizes {
  358. fooWriteBytes = append(fooWriteBytes, cmn.RandBytes(size))
  359. }
  360. // Consume reads from bar's reader
  361. go func() {
  362. readBuffer := make([]byte, dataMaxSize)
  363. for {
  364. _, err := barSecConn.Read(readBuffer)
  365. if err == io.EOF {
  366. return
  367. } else if err != nil {
  368. b.Fatalf("Failed to read from barSecConn: %v", err)
  369. }
  370. }
  371. }()
  372. b.StartTimer()
  373. for i := 0; i < b.N; i++ {
  374. idx := cmn.RandIntn(len(fooWriteBytes))
  375. _, err := fooSecConn.Write(fooWriteBytes[idx])
  376. if err != nil {
  377. b.Fatalf("Failed to write to fooSecConn: %v", err)
  378. }
  379. }
  380. b.StopTimer()
  381. if err := fooSecConn.Close(); err != nil {
  382. b.Error(err)
  383. }
  384. //barSecConn.Close() race condition
  385. }
  386. func BenchmarkReadSecretConnection(b *testing.B) {
  387. b.StopTimer()
  388. b.ReportAllocs()
  389. fooSecConn, barSecConn := makeSecretConnPair(b)
  390. randomMsgSizes := []int{
  391. dataMaxSize / 10,
  392. dataMaxSize / 3,
  393. dataMaxSize / 2,
  394. dataMaxSize,
  395. dataMaxSize * 3 / 2,
  396. dataMaxSize * 2,
  397. dataMaxSize * 7 / 2,
  398. }
  399. fooWriteBytes := make([][]byte, 0, len(randomMsgSizes))
  400. for _, size := range randomMsgSizes {
  401. fooWriteBytes = append(fooWriteBytes, cmn.RandBytes(size))
  402. }
  403. go func() {
  404. for i := 0; i < b.N; i++ {
  405. idx := cmn.RandIntn(len(fooWriteBytes))
  406. _, err := fooSecConn.Write(fooWriteBytes[idx])
  407. if err != nil {
  408. b.Fatalf("Failed to write to fooSecConn: %v, %v,%v", err, i, b.N)
  409. }
  410. }
  411. }()
  412. b.StartTimer()
  413. for i := 0; i < b.N; i++ {
  414. readBuffer := make([]byte, dataMaxSize)
  415. _, err := barSecConn.Read(readBuffer)
  416. if err == io.EOF {
  417. return
  418. } else if err != nil {
  419. b.Fatalf("Failed to read from barSecConn: %v", err)
  420. }
  421. }
  422. b.StopTimer()
  423. }