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.

184 lines
5.1 KiB

crypto: fix infinite recursion in Secp256k1 string formatting (#5707) This caused stack overflow panics in E2E tests, e.g.: ``` 2020-11-24T02:37:17.6085640Z validator04 | runtime: goroutine stack exceeds 1000000000-byte limit 2020-11-24T02:37:17.6087818Z validator04 | runtime: sp=0xc0234b23c0 stack=[0xc0234b2000, 0xc0434b2000] 2020-11-24T02:37:17.6088920Z validator04 | fatal error: stack overflow 2020-11-24T02:37:17.6089776Z validator04 | 2020-11-24T02:37:17.6090569Z validator04 | runtime stack: 2020-11-24T02:37:17.6091677Z validator04 | runtime.throw(0x12dc476, 0xe) 2020-11-24T02:37:17.6093123Z validator04 | /usr/local/go/src/runtime/panic.go:1116 +0x72 2020-11-24T02:37:17.6094320Z validator04 | runtime.newstack() 2020-11-24T02:37:17.6095374Z validator04 | /usr/local/go/src/runtime/stack.go:1067 +0x78d 2020-11-24T02:37:17.6096381Z validator04 | runtime.morestack() 2020-11-24T02:37:17.6097657Z validator04 | /usr/local/go/src/runtime/asm_amd64.s:449 +0x8f 2020-11-24T02:37:17.6098505Z validator04 | 2020-11-24T02:37:17.6099328Z validator04 | goroutine 88 [running]: 2020-11-24T02:37:17.6100470Z validator04 | runtime.heapBitsSetType(0xc009565380, 0x20, 0x18, 0x1137e00) 2020-11-24T02:37:17.6101961Z validator04 | /usr/local/go/src/runtime/mbitmap.go:911 +0xaa5 fp=0xc0234b23d0 sp=0xc0234b23c8 pc=0x432625 2020-11-24T02:37:17.6103906Z validator04 | runtime.mallocgc(0x20, 0x1137e00, 0x117b601, 0x11e9240) 2020-11-24T02:37:17.6105179Z validator04 | /usr/local/go/src/runtime/malloc.go:1090 +0x5a5 fp=0xc0234b2470 sp=0xc0234b23d0 pc=0x428b25 2020-11-24T02:37:17.6106540Z validator04 | runtime.convTslice(0xc002743710, 0x21, 0x21, 0xc0234b24e8) 2020-11-24T02:37:17.6107861Z validator04 | /usr/local/go/src/runtime/iface.go:385 +0x59 fp=0xc0234b24a0 sp=0xc0234b2470 pc=0x426379 2020-11-24T02:37:17.6109315Z validator04 | github.com/tendermint/tendermint/crypto/secp256k1.PubKey.String(...) 2020-11-24T02:37:17.6151692Z validator04 | /src/tendermint/crypto/secp256k1/secp256k1.go:161 2020-11-24T02:37:17.6153872Z validator04 | github.com/tendermint/tendermint/crypto/secp256k1.(*PubKey).String(0xc009565360, 0x11e9240, 0xc009565360) 2020-11-24T02:37:17.6157421Z validator04 | <autogenerated>:1 +0x65 fp=0xc0234b24f8 sp=0xc0234b24a0 pc=0x656965 2020-11-24T02:37:17.6159134Z validator04 | fmt.(*pp).handleMethods(0xc00956c680, 0x58, 0xc0234b2801) 2020-11-24T02:37:17.6161462Z validator04 | /usr/local/go/src/fmt/print.go:630 +0x30a fp=0xc0234b2768 sp=0xc0234b24f8 pc=0x518b8a [...] 2020-11-24T02:37:17.6649685Z validator04 | /usr/local/go/src/fmt/print.go:630 +0x30a fp=0xc0234b7f48 sp=0xc0234b7cd8 pc=0x518b8a 2020-11-24T02:37:17.6651177Z validator04 | created by github.com/tendermint/tendermint/node.startStateSync 2020-11-24T02:37:17.6652521Z validator04 | /src/tendermint/node/node.go:587 +0x150 ```
4 years ago
  1. package secp256k1
  2. import (
  3. "bytes"
  4. "crypto/sha256"
  5. "crypto/subtle"
  6. "fmt"
  7. "io"
  8. "math/big"
  9. secp256k1 "github.com/btcsuite/btcd/btcec"
  10. "github.com/tendermint/tendermint/crypto"
  11. "github.com/tendermint/tendermint/internal/jsontypes"
  12. tmjson "github.com/tendermint/tendermint/libs/json"
  13. // necessary for Bitcoin address format
  14. "golang.org/x/crypto/ripemd160" // nolint
  15. )
  16. //-------------------------------------
  17. const (
  18. PrivKeyName = "tendermint/PrivKeySecp256k1"
  19. PubKeyName = "tendermint/PubKeySecp256k1"
  20. KeyType = "secp256k1"
  21. PrivKeySize = 32
  22. )
  23. func init() {
  24. tmjson.RegisterType(PubKey{}, PubKeyName)
  25. tmjson.RegisterType(PrivKey{}, PrivKeyName)
  26. jsontypes.MustRegister(PubKey{})
  27. jsontypes.MustRegister(PrivKey{})
  28. }
  29. var _ crypto.PrivKey = PrivKey{}
  30. // PrivKey implements PrivKey.
  31. type PrivKey []byte
  32. // TypeTag satisfies the jsontypes.Tagged interface.
  33. func (PrivKey) TypeTag() string { return PrivKeyName }
  34. // Bytes marshalls the private key using amino encoding.
  35. func (privKey PrivKey) Bytes() []byte {
  36. return []byte(privKey)
  37. }
  38. // PubKey performs the point-scalar multiplication from the privKey on the
  39. // generator point to get the pubkey.
  40. func (privKey PrivKey) PubKey() crypto.PubKey {
  41. _, pubkeyObject := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey)
  42. pk := pubkeyObject.SerializeCompressed()
  43. return PubKey(pk)
  44. }
  45. // Equals - you probably don't need to use this.
  46. // Runs in constant time based on length of the keys.
  47. func (privKey PrivKey) Equals(other crypto.PrivKey) bool {
  48. if otherSecp, ok := other.(PrivKey); ok {
  49. return subtle.ConstantTimeCompare(privKey[:], otherSecp[:]) == 1
  50. }
  51. return false
  52. }
  53. func (privKey PrivKey) Type() string {
  54. return KeyType
  55. }
  56. // GenPrivKey generates a new ECDSA private key on curve secp256k1 private key.
  57. // It uses OS randomness to generate the private key.
  58. func GenPrivKey() PrivKey {
  59. return genPrivKey(crypto.CReader())
  60. }
  61. // genPrivKey generates a new secp256k1 private key using the provided reader.
  62. func genPrivKey(rand io.Reader) PrivKey {
  63. var privKeyBytes [PrivKeySize]byte
  64. d := new(big.Int)
  65. for {
  66. privKeyBytes = [PrivKeySize]byte{}
  67. _, err := io.ReadFull(rand, privKeyBytes[:])
  68. if err != nil {
  69. panic(err)
  70. }
  71. d.SetBytes(privKeyBytes[:])
  72. // break if we found a valid point (i.e. > 0 and < N == curverOrder)
  73. isValidFieldElement := 0 < d.Sign() && d.Cmp(secp256k1.S256().N) < 0
  74. if isValidFieldElement {
  75. break
  76. }
  77. }
  78. return PrivKey(privKeyBytes[:])
  79. }
  80. var one = new(big.Int).SetInt64(1)
  81. // GenPrivKeySecp256k1 hashes the secret with SHA2, and uses
  82. // that 32 byte output to create the private key.
  83. //
  84. // It makes sure the private key is a valid field element by setting:
  85. //
  86. // c = sha256(secret)
  87. // k = (c mod (n − 1)) + 1, where n = curve order.
  88. //
  89. // NOTE: secret should be the output of a KDF like bcrypt,
  90. // if it's derived from user input.
  91. func GenPrivKeySecp256k1(secret []byte) PrivKey {
  92. secHash := sha256.Sum256(secret)
  93. // to guarantee that we have a valid field element, we use the approach of:
  94. // "Suite B Implementer’s Guide to FIPS 186-3", A.2.1
  95. // https://apps.nsa.gov/iaarchive/library/ia-guidance/ia-solutions-for-classified/algorithm-guidance/suite-b-implementers-guide-to-fips-186-3-ecdsa.cfm
  96. // see also https://github.com/golang/go/blob/0380c9ad38843d523d9c9804fe300cb7edd7cd3c/src/crypto/ecdsa/ecdsa.go#L89-L101
  97. fe := new(big.Int).SetBytes(secHash[:])
  98. n := new(big.Int).Sub(secp256k1.S256().N, one)
  99. fe.Mod(fe, n)
  100. fe.Add(fe, one)
  101. feB := fe.Bytes()
  102. privKey32 := make([]byte, PrivKeySize)
  103. // copy feB over to fixed 32 byte privKey32 and pad (if necessary)
  104. copy(privKey32[32-len(feB):32], feB)
  105. return PrivKey(privKey32)
  106. }
  107. //-------------------------------------
  108. var _ crypto.PubKey = PubKey{}
  109. // PubKeySize is comprised of 32 bytes for one field element
  110. // (the x-coordinate), plus one byte for the parity of the y-coordinate.
  111. const PubKeySize = 33
  112. // PubKey implements crypto.PubKey.
  113. // It is the compressed form of the pubkey. The first byte depends is a 0x02 byte
  114. // if the y-coordinate is the lexicographically largest of the two associated with
  115. // the x-coordinate. Otherwise the first byte is a 0x03.
  116. // This prefix is followed with the x-coordinate.
  117. type PubKey []byte
  118. // TypeTag satisfies the jsontypes.Tagged interface.
  119. func (PubKey) TypeTag() string { return PubKeyName }
  120. // Address returns a Bitcoin style addresses: RIPEMD160(SHA256(pubkey))
  121. func (pubKey PubKey) Address() crypto.Address {
  122. if len(pubKey) != PubKeySize {
  123. panic("length of pubkey is incorrect")
  124. }
  125. hasherSHA256 := sha256.New()
  126. _, _ = hasherSHA256.Write(pubKey) // does not error
  127. sha := hasherSHA256.Sum(nil)
  128. hasherRIPEMD160 := ripemd160.New()
  129. _, _ = hasherRIPEMD160.Write(sha) // does not error
  130. return crypto.Address(hasherRIPEMD160.Sum(nil))
  131. }
  132. // Bytes returns the pubkey marshaled with amino encoding.
  133. func (pubKey PubKey) Bytes() []byte {
  134. return []byte(pubKey)
  135. }
  136. func (pubKey PubKey) String() string {
  137. return fmt.Sprintf("PubKeySecp256k1{%X}", []byte(pubKey))
  138. }
  139. func (pubKey PubKey) Equals(other crypto.PubKey) bool {
  140. if otherSecp, ok := other.(PubKey); ok {
  141. return bytes.Equal(pubKey[:], otherSecp[:])
  142. }
  143. return false
  144. }
  145. func (pubKey PubKey) Type() string {
  146. return KeyType
  147. }