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.

245 lines
7.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. // necessary for Bitcoin address format
  13. "golang.org/x/crypto/ripemd160" //nolint:staticcheck
  14. )
  15. //-------------------------------------
  16. const (
  17. PrivKeyName = "tendermint/PrivKeySecp256k1"
  18. PubKeyName = "tendermint/PubKeySecp256k1"
  19. KeyType = "secp256k1"
  20. PrivKeySize = 32
  21. )
  22. func init() {
  23. jsontypes.MustRegister(PubKey{})
  24. jsontypes.MustRegister(PrivKey{})
  25. }
  26. var _ crypto.PrivKey = PrivKey{}
  27. // PrivKey implements PrivKey.
  28. type PrivKey []byte
  29. // TypeTag satisfies the jsontypes.Tagged interface.
  30. func (PrivKey) TypeTag() string { return PrivKeyName }
  31. // Bytes marshalls the private key using amino encoding.
  32. func (privKey PrivKey) Bytes() []byte {
  33. return []byte(privKey)
  34. }
  35. // PubKey performs the point-scalar multiplication from the privKey on the
  36. // generator point to get the pubkey.
  37. func (privKey PrivKey) PubKey() crypto.PubKey {
  38. _, pubkeyObject := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey)
  39. pk := pubkeyObject.SerializeCompressed()
  40. return PubKey(pk)
  41. }
  42. // Equals - you probably don't need to use this.
  43. // Runs in constant time based on length of the keys.
  44. func (privKey PrivKey) Equals(other crypto.PrivKey) bool {
  45. if otherSecp, ok := other.(PrivKey); ok {
  46. return subtle.ConstantTimeCompare(privKey[:], otherSecp[:]) == 1
  47. }
  48. return false
  49. }
  50. func (privKey PrivKey) Type() string {
  51. return KeyType
  52. }
  53. // GenPrivKey generates a new ECDSA private key on curve secp256k1 private key.
  54. // It uses OS randomness to generate the private key.
  55. func GenPrivKey() PrivKey {
  56. return genPrivKey(crypto.CReader())
  57. }
  58. // genPrivKey generates a new secp256k1 private key using the provided reader.
  59. func genPrivKey(rand io.Reader) PrivKey {
  60. var privKeyBytes [PrivKeySize]byte
  61. d := new(big.Int)
  62. for {
  63. privKeyBytes = [PrivKeySize]byte{}
  64. _, err := io.ReadFull(rand, privKeyBytes[:])
  65. if err != nil {
  66. panic(err)
  67. }
  68. d.SetBytes(privKeyBytes[:])
  69. // break if we found a valid point (i.e. > 0 and < N == curverOrder)
  70. isValidFieldElement := 0 < d.Sign() && d.Cmp(secp256k1.S256().N) < 0
  71. if isValidFieldElement {
  72. break
  73. }
  74. }
  75. return PrivKey(privKeyBytes[:])
  76. }
  77. var one = new(big.Int).SetInt64(1)
  78. // GenPrivKeySecp256k1 hashes the secret with SHA2, and uses
  79. // that 32 byte output to create the private key.
  80. //
  81. // It makes sure the private key is a valid field element by setting:
  82. //
  83. // c = sha256(secret)
  84. // k = (c mod (n − 1)) + 1, where n = curve order.
  85. //
  86. // NOTE: secret should be the output of a KDF like bcrypt,
  87. // if it's derived from user input.
  88. func GenPrivKeySecp256k1(secret []byte) PrivKey {
  89. secHash := sha256.Sum256(secret)
  90. // to guarantee that we have a valid field element, we use the approach of:
  91. // "Suite B Implementer’s Guide to FIPS 186-3", A.2.1
  92. // https://apps.nsa.gov/iaarchive/library/ia-guidance/ia-solutions-for-classified/algorithm-guidance/suite-b-implementers-guide-to-fips-186-3-ecdsa.cfm
  93. // see also https://github.com/golang/go/blob/0380c9ad38843d523d9c9804fe300cb7edd7cd3c/src/crypto/ecdsa/ecdsa.go#L89-L101
  94. fe := new(big.Int).SetBytes(secHash[:])
  95. n := new(big.Int).Sub(secp256k1.S256().N, one)
  96. fe.Mod(fe, n)
  97. fe.Add(fe, one)
  98. feB := fe.Bytes()
  99. privKey32 := make([]byte, PrivKeySize)
  100. // copy feB over to fixed 32 byte privKey32 and pad (if necessary)
  101. copy(privKey32[32-len(feB):32], feB)
  102. return PrivKey(privKey32)
  103. }
  104. //-------------------------------------
  105. var _ crypto.PubKey = PubKey{}
  106. // PubKeySize is comprised of 32 bytes for one field element
  107. // (the x-coordinate), plus one byte for the parity of the y-coordinate.
  108. const PubKeySize = 33
  109. // PubKey implements crypto.PubKey.
  110. // It is the compressed form of the pubkey. The first byte depends is a 0x02 byte
  111. // if the y-coordinate is the lexicographically largest of the two associated with
  112. // the x-coordinate. Otherwise the first byte is a 0x03.
  113. // This prefix is followed with the x-coordinate.
  114. type PubKey []byte
  115. // TypeTag satisfies the jsontypes.Tagged interface.
  116. func (PubKey) TypeTag() string { return PubKeyName }
  117. // Address returns a Bitcoin style addresses: RIPEMD160(SHA256(pubkey))
  118. func (pubKey PubKey) Address() crypto.Address {
  119. if len(pubKey) != PubKeySize {
  120. panic("length of pubkey is incorrect")
  121. }
  122. hasherSHA256 := sha256.New()
  123. _, _ = hasherSHA256.Write(pubKey) // does not error
  124. sha := hasherSHA256.Sum(nil)
  125. hasherRIPEMD160 := ripemd160.New()
  126. _, _ = hasherRIPEMD160.Write(sha) // does not error
  127. return crypto.Address(hasherRIPEMD160.Sum(nil))
  128. }
  129. // Bytes returns the pubkey marshaled with amino encoding.
  130. func (pubKey PubKey) Bytes() []byte {
  131. return []byte(pubKey)
  132. }
  133. func (pubKey PubKey) String() string {
  134. return fmt.Sprintf("PubKeySecp256k1{%X}", []byte(pubKey))
  135. }
  136. func (pubKey PubKey) Equals(other crypto.PubKey) bool {
  137. if otherSecp, ok := other.(PubKey); ok {
  138. return bytes.Equal(pubKey[:], otherSecp[:])
  139. }
  140. return false
  141. }
  142. func (pubKey PubKey) Type() string {
  143. return KeyType
  144. }
  145. // used to reject malleable signatures
  146. // see:
  147. // - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93
  148. // - https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/crypto.go#L39
  149. var secp256k1halfN = new(big.Int).Rsh(secp256k1.S256().N, 1)
  150. // Sign creates an ECDSA signature on curve Secp256k1, using SHA256 on the msg.
  151. // The returned signature will be of the form R || S (in lower-S form).
  152. func (privKey PrivKey) Sign(msg []byte) ([]byte, error) {
  153. priv, _ := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey)
  154. sig, err := priv.Sign(crypto.Sha256(msg))
  155. if err != nil {
  156. return nil, err
  157. }
  158. sigBytes := serializeSig(sig)
  159. return sigBytes, nil
  160. }
  161. // VerifySignature verifies a signature of the form R || S.
  162. // It rejects signatures which are not in lower-S form.
  163. func (pubKey PubKey) VerifySignature(msg []byte, sigStr []byte) bool {
  164. if len(sigStr) != 64 {
  165. return false
  166. }
  167. pub, err := secp256k1.ParsePubKey(pubKey, secp256k1.S256())
  168. if err != nil {
  169. return false
  170. }
  171. // parse the signature:
  172. signature := signatureFromBytes(sigStr)
  173. // Reject malleable signatures. libsecp256k1 does this check but btcec doesn't.
  174. // see: https://github.com/ethereum/go-ethereum/blob/f9401ae011ddf7f8d2d95020b7446c17f8d98dc1/crypto/signature_nocgo.go#L90-L93
  175. if signature.S.Cmp(secp256k1halfN) > 0 {
  176. return false
  177. }
  178. return signature.Verify(crypto.Sha256(msg), pub)
  179. }
  180. // Read Signature struct from R || S. Caller needs to ensure
  181. // that len(sigStr) == 64.
  182. func signatureFromBytes(sigStr []byte) *secp256k1.Signature {
  183. return &secp256k1.Signature{
  184. R: new(big.Int).SetBytes(sigStr[:32]),
  185. S: new(big.Int).SetBytes(sigStr[32:64]),
  186. }
  187. }
  188. // Serialize signature to R || S.
  189. // R, S are padded to 32 bytes respectively.
  190. func serializeSig(sig *secp256k1.Signature) []byte {
  191. rBytes := sig.R.Bytes()
  192. sBytes := sig.S.Bytes()
  193. sigBytes := make([]byte, 64)
  194. // 0 pad the byte arrays from the left if they aren't big enough.
  195. copy(sigBytes[32-len(rBytes):32], rBytes)
  196. copy(sigBytes[64-len(sBytes):64], sBytes)
  197. return sigBytes
  198. }