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.

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