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.

173 lines
4.8 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. "golang.org/x/crypto/ripemd160" // nolint: staticcheck // necessary for Bitcoin address format
  11. "github.com/tendermint/tendermint/crypto"
  12. tmjson "github.com/tendermint/tendermint/libs/json"
  13. )
  14. //-------------------------------------
  15. const (
  16. PrivKeyName = "tendermint/PrivKeySecp256k1"
  17. PubKeyName = "tendermint/PubKeySecp256k1"
  18. KeyType = "secp256k1"
  19. PrivKeySize = 32
  20. )
  21. func init() {
  22. tmjson.RegisterType(PubKey{}, PubKeyName)
  23. tmjson.RegisterType(PrivKey{}, PrivKeyName)
  24. }
  25. var _ crypto.PrivKey = PrivKey{}
  26. // PrivKey implements PrivKey.
  27. type PrivKey []byte
  28. // Bytes marshalls the private key using amino encoding.
  29. func (privKey PrivKey) Bytes() []byte {
  30. return []byte(privKey)
  31. }
  32. // PubKey performs the point-scalar multiplication from the privKey on the
  33. // generator point to get the pubkey.
  34. func (privKey PrivKey) PubKey() crypto.PubKey {
  35. _, pubkeyObject := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey)
  36. pk := pubkeyObject.SerializeCompressed()
  37. return PubKey(pk)
  38. }
  39. // Equals - you probably don't need to use this.
  40. // Runs in constant time based on length of the keys.
  41. func (privKey PrivKey) Equals(other crypto.PrivKey) bool {
  42. if otherSecp, ok := other.(PrivKey); ok {
  43. return subtle.ConstantTimeCompare(privKey[:], otherSecp[:]) == 1
  44. }
  45. return false
  46. }
  47. func (privKey PrivKey) Type() string {
  48. return KeyType
  49. }
  50. // GenPrivKey generates a new ECDSA private key on curve secp256k1 private key.
  51. // It uses OS randomness to generate the private key.
  52. func GenPrivKey() PrivKey {
  53. return genPrivKey(crypto.CReader())
  54. }
  55. // genPrivKey generates a new secp256k1 private key using the provided reader.
  56. func genPrivKey(rand io.Reader) PrivKey {
  57. var privKeyBytes [PrivKeySize]byte
  58. d := new(big.Int)
  59. for {
  60. privKeyBytes = [PrivKeySize]byte{}
  61. _, err := io.ReadFull(rand, privKeyBytes[:])
  62. if err != nil {
  63. panic(err)
  64. }
  65. d.SetBytes(privKeyBytes[:])
  66. // break if we found a valid point (i.e. > 0 and < N == curverOrder)
  67. isValidFieldElement := 0 < d.Sign() && d.Cmp(secp256k1.S256().N) < 0
  68. if isValidFieldElement {
  69. break
  70. }
  71. }
  72. return PrivKey(privKeyBytes[:])
  73. }
  74. var one = new(big.Int).SetInt64(1)
  75. // GenPrivKeySecp256k1 hashes the secret with SHA2, and uses
  76. // that 32 byte output to create the private key.
  77. //
  78. // It makes sure the private key is a valid field element by setting:
  79. //
  80. // c = sha256(secret)
  81. // k = (c mod (n − 1)) + 1, where n = curve order.
  82. //
  83. // NOTE: secret should be the output of a KDF like bcrypt,
  84. // if it's derived from user input.
  85. func GenPrivKeySecp256k1(secret []byte) PrivKey {
  86. secHash := sha256.Sum256(secret)
  87. // to guarantee that we have a valid field element, we use the approach of:
  88. // "Suite B Implementer’s Guide to FIPS 186-3", A.2.1
  89. // https://apps.nsa.gov/iaarchive/library/ia-guidance/ia-solutions-for-classified/algorithm-guidance/suite-b-implementers-guide-to-fips-186-3-ecdsa.cfm
  90. // see also https://github.com/golang/go/blob/0380c9ad38843d523d9c9804fe300cb7edd7cd3c/src/crypto/ecdsa/ecdsa.go#L89-L101
  91. fe := new(big.Int).SetBytes(secHash[:])
  92. n := new(big.Int).Sub(secp256k1.S256().N, one)
  93. fe.Mod(fe, n)
  94. fe.Add(fe, one)
  95. feB := fe.Bytes()
  96. privKey32 := make([]byte, PrivKeySize)
  97. // copy feB over to fixed 32 byte privKey32 and pad (if necessary)
  98. copy(privKey32[32-len(feB):32], feB)
  99. return PrivKey(privKey32)
  100. }
  101. //-------------------------------------
  102. var _ crypto.PubKey = PubKey{}
  103. // PubKeySize is comprised of 32 bytes for one field element
  104. // (the x-coordinate), plus one byte for the parity of the y-coordinate.
  105. const PubKeySize = 33
  106. // PubKey implements crypto.PubKey.
  107. // It is the compressed form of the pubkey. The first byte depends is a 0x02 byte
  108. // if the y-coordinate is the lexicographically largest of the two associated with
  109. // the x-coordinate. Otherwise the first byte is a 0x03.
  110. // This prefix is followed with the x-coordinate.
  111. type PubKey []byte
  112. // Address returns a Bitcoin style addresses: RIPEMD160(SHA256(pubkey))
  113. func (pubKey PubKey) Address() crypto.Address {
  114. if len(pubKey) != PubKeySize {
  115. panic("length of pubkey is incorrect")
  116. }
  117. hasherSHA256 := sha256.New()
  118. _, _ = hasherSHA256.Write(pubKey) // does not error
  119. sha := hasherSHA256.Sum(nil)
  120. hasherRIPEMD160 := ripemd160.New()
  121. _, _ = hasherRIPEMD160.Write(sha) // does not error
  122. return crypto.Address(hasherRIPEMD160.Sum(nil))
  123. }
  124. // Bytes returns the pubkey marshaled with amino encoding.
  125. func (pubKey PubKey) Bytes() []byte {
  126. return []byte(pubKey)
  127. }
  128. func (pubKey PubKey) String() string {
  129. return fmt.Sprintf("PubKeySecp256k1{%X}", []byte(pubKey))
  130. }
  131. func (pubKey PubKey) Equals(other crypto.PubKey) bool {
  132. if otherSecp, ok := other.(PubKey); ok {
  133. return bytes.Equal(pubKey[:], otherSecp[:])
  134. }
  135. return false
  136. }
  137. func (pubKey PubKey) Type() string {
  138. return KeyType
  139. }