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.

411 lines
17 KiB

  1. package light
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "time"
  8. "github.com/tendermint/tendermint/light/provider"
  9. "github.com/tendermint/tendermint/types"
  10. )
  11. // The detector component of the light client detects and handles attacks on the light client.
  12. // More info here:
  13. // tendermint/docs/architecture/adr-047-handling-evidence-from-light-client.md
  14. // detectDivergence is a second wall of defense for the light client.
  15. //
  16. // It takes the target verified header and compares it with the headers of a set of
  17. // witness providers that the light client is connected to. If a conflicting header
  18. // is returned it verifies and examines the conflicting header against the verified
  19. // trace that was produced from the primary. If successful, it produces two sets of evidence
  20. // and sends them to the opposite provider before halting.
  21. //
  22. // If there are no conflictinge headers, the light client deems the verified target header
  23. // trusted and saves it to the trusted store.
  24. func (c *Client) detectDivergence(ctx context.Context, primaryTrace []*types.LightBlock, now time.Time) error {
  25. if primaryTrace == nil || len(primaryTrace) < 2 {
  26. return errors.New("nil or single block primary trace")
  27. }
  28. var (
  29. headerMatched bool
  30. lastVerifiedHeader = primaryTrace[len(primaryTrace)-1].SignedHeader
  31. witnessesToRemove = make([]int, 0)
  32. )
  33. c.logger.Debug("running detector against trace", "endBlockHeight", lastVerifiedHeader.Height,
  34. "endBlockHash", lastVerifiedHeader.Hash, "length", len(primaryTrace))
  35. c.providerMutex.Lock()
  36. defer c.providerMutex.Unlock()
  37. if len(c.witnesses) == 0 {
  38. return ErrNoWitnesses
  39. }
  40. // launch one goroutine per witness to retrieve the light block of the target height
  41. // and compare it with the header from the primary
  42. errc := make(chan error, len(c.witnesses))
  43. for i, witness := range c.witnesses {
  44. go c.compareNewHeaderWithWitness(ctx, errc, lastVerifiedHeader, witness, i)
  45. }
  46. // handle errors from the header comparisons as they come in
  47. for i := 0; i < cap(errc); i++ {
  48. err := <-errc
  49. switch e := err.(type) {
  50. case nil: // at least one header matched
  51. headerMatched = true
  52. case errConflictingHeaders:
  53. // We have conflicting headers. This could possibly imply an attack on the light client.
  54. // First we need to verify the witness's header using the same skipping verification and then we
  55. // need to find the point that the headers diverge and examine this for any evidence of an attack.
  56. //
  57. // We combine these actions together, verifying the witnesses headers and outputting the trace
  58. // which captures the bifurcation point and if successful provides the information to create valid evidence.
  59. err := c.handleConflictingHeaders(ctx, primaryTrace, e.Block, e.WitnessIndex, now)
  60. if err != nil {
  61. // return information of the attack
  62. return err
  63. }
  64. // if attempt to generate conflicting headers failed then remove witness
  65. witnessesToRemove = append(witnessesToRemove, e.WitnessIndex)
  66. case errBadWitness:
  67. c.logger.Info("witness returned an error during header comparison, removing...",
  68. "witness", c.witnesses[e.WitnessIndex], "err", err)
  69. witnessesToRemove = append(witnessesToRemove, e.WitnessIndex)
  70. default:
  71. c.logger.Debug("error in light block request to witness", "err", err)
  72. }
  73. }
  74. // remove witnesses that have misbehaved
  75. if err := c.removeWitnesses(witnessesToRemove); err != nil {
  76. return err
  77. }
  78. // 1. If we had at least one witness that returned the same header then we
  79. // conclude that we can trust the header
  80. if headerMatched {
  81. return nil
  82. }
  83. // 2. Else all witnesses have either not responded, don't have the block or sent invalid blocks.
  84. return ErrFailedHeaderCrossReferencing
  85. }
  86. // compareNewHeaderWithWitness takes the verified header from the primary and compares it with a
  87. // header from a specified witness. The function can return one of three errors:
  88. //
  89. // 1: errConflictingHeaders -> there may have been an attack on this light client
  90. // 2: errBadWitness -> the witness has either not responded, doesn't have the header or has given us an invalid one
  91. // Note: In the case of an invalid header we remove the witness
  92. // 3: nil -> the hashes of the two headers match
  93. func (c *Client) compareNewHeaderWithWitness(ctx context.Context, errc chan error, h *types.SignedHeader,
  94. witness provider.Provider, witnessIndex int) {
  95. lightBlock, err := witness.LightBlock(ctx, h.Height)
  96. switch err {
  97. // no error means we move on to checking the hash of the two headers
  98. case nil:
  99. break
  100. // the witness hasn't been helpful in comparing headers, we mark the response and continue
  101. // comparing with the rest of the witnesses
  102. case provider.ErrNoResponse, provider.ErrLightBlockNotFound:
  103. errc <- err
  104. return
  105. // the witness' head of the blockchain is lower than the height of the primary. This could be one of
  106. // two things:
  107. // 1) The witness is lagging behind
  108. // 2) The primary may be performing a lunatic attack with a height and time in the future
  109. case provider.ErrHeightTooHigh:
  110. // The light client now asks for the latest header that the witness has
  111. var isTargetHeight bool
  112. isTargetHeight, lightBlock, err = c.getTargetBlockOrLatest(ctx, h.Height, witness)
  113. if err != nil {
  114. errc <- err
  115. return
  116. }
  117. // if the witness caught up and has returned a block of the target height then we can
  118. // break from this switch case and continue to verify the hashes
  119. if isTargetHeight {
  120. break
  121. }
  122. // witness' last header is below the primary's header. We check the times to see if the blocks
  123. // have conflicting times
  124. if !lightBlock.Time.Before(h.Time) {
  125. errc <- errConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex}
  126. return
  127. }
  128. // the witness is behind. We wait for a period WAITING = 2 * DRIFT + LAG.
  129. // This should give the witness ample time if it is a participating member
  130. // of consensus to produce a block that has a time that is after the primary's
  131. // block time. If not the witness is too far behind and the light client removes it
  132. time.Sleep(2*c.maxClockDrift + c.maxBlockLag)
  133. isTargetHeight, lightBlock, err = c.getTargetBlockOrLatest(ctx, h.Height, witness)
  134. if err != nil {
  135. errc <- errBadWitness{Reason: err, WitnessIndex: witnessIndex}
  136. return
  137. }
  138. if isTargetHeight {
  139. break
  140. }
  141. // the witness still doesn't have a block at the height of the primary.
  142. // Check if there is a conflicting time
  143. if !lightBlock.Time.Before(h.Time) {
  144. errc <- errConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex}
  145. return
  146. }
  147. // Following this request response procedure, the witness has been unable to produce a block
  148. // that can somehow conflict with the primary's block. We thus conclude that the witness
  149. // is too far behind and thus we return a no response error.
  150. //
  151. // NOTE: If the clock drift / lag has been miscalibrated it is feasible that the light client has
  152. // drifted too far ahead for any witness to be able provide a comparable block and thus may allow
  153. // for a malicious primary to attack it
  154. errc <- provider.ErrNoResponse
  155. return
  156. default:
  157. // all other errors (i.e. invalid block, closed connection or unreliable provider) we mark the
  158. // witness as bad and remove it
  159. errc <- errBadWitness{Reason: err, WitnessIndex: witnessIndex}
  160. return
  161. }
  162. if !bytes.Equal(h.Hash(), lightBlock.Hash()) {
  163. errc <- errConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex}
  164. }
  165. c.logger.Debug("matching header received by witness", "height", h.Height, "witness", witnessIndex)
  166. errc <- nil
  167. }
  168. // sendEvidence sends evidence to a provider on a best effort basis.
  169. func (c *Client) sendEvidence(ctx context.Context, ev *types.LightClientAttackEvidence, receiver provider.Provider) {
  170. err := receiver.ReportEvidence(ctx, ev)
  171. if err != nil {
  172. c.logger.Error("failed to report evidence to provider", "ev", ev, "provider", receiver)
  173. }
  174. }
  175. // handleConflictingHeaders handles the primary style of attack, which is where a primary and witness have
  176. // two headers of the same height but with different hashes
  177. func (c *Client) handleConflictingHeaders(
  178. ctx context.Context,
  179. primaryTrace []*types.LightBlock,
  180. challendingBlock *types.LightBlock,
  181. witnessIndex int,
  182. now time.Time,
  183. ) error {
  184. supportingWitness := c.witnesses[witnessIndex]
  185. witnessTrace, primaryBlock, err := c.examineConflictingHeaderAgainstTrace(
  186. ctx,
  187. primaryTrace,
  188. challendingBlock,
  189. supportingWitness,
  190. now,
  191. )
  192. if err != nil {
  193. c.logger.Info("error validating witness's divergent header", "witness", supportingWitness, "err", err)
  194. return nil
  195. }
  196. // We are suspecting that the primary is faulty, hence we hold the witness as the source of truth
  197. // and generate evidence against the primary that we can send to the witness
  198. commonBlock, trustedBlock := witnessTrace[0], witnessTrace[len(witnessTrace)-1]
  199. evidenceAgainstPrimary := newLightClientAttackEvidence(primaryBlock, trustedBlock, commonBlock)
  200. c.logger.Error("ATTEMPTED ATTACK DETECTED. Sending evidence againt primary by witness", "ev", evidenceAgainstPrimary,
  201. "primary", c.primary, "witness", supportingWitness)
  202. c.sendEvidence(ctx, evidenceAgainstPrimary, supportingWitness)
  203. if primaryBlock.Commit.Round != witnessTrace[len(witnessTrace)-1].Commit.Round {
  204. c.logger.Info("The light client has detected, and prevented, an attempted amnesia attack." +
  205. " We think this attack is pretty unlikely, so if you see it, that's interesting to us." +
  206. " Can you let us know by opening an issue through https://github.com/tendermint/tendermint/issues/new?")
  207. }
  208. // This may not be valid because the witness itself is at fault. So now we reverse it, examining the
  209. // trace provided by the witness and holding the primary as the source of truth. Note: primary may not
  210. // respond but this is okay as we will halt anyway.
  211. primaryTrace, witnessBlock, err := c.examineConflictingHeaderAgainstTrace(
  212. ctx,
  213. witnessTrace,
  214. primaryBlock,
  215. c.primary,
  216. now,
  217. )
  218. if err != nil {
  219. c.logger.Info("Error validating primary's divergent header", "primary", c.primary, "err", err)
  220. return ErrLightClientAttack
  221. }
  222. // We now use the primary trace to create evidence against the witness and send it to the primary
  223. commonBlock, trustedBlock = primaryTrace[0], primaryTrace[len(primaryTrace)-1]
  224. evidenceAgainstWitness := newLightClientAttackEvidence(witnessBlock, trustedBlock, commonBlock)
  225. c.logger.Error("Sending evidence against witness by primary", "ev", evidenceAgainstWitness,
  226. "primary", c.primary, "witness", supportingWitness)
  227. c.sendEvidence(ctx, evidenceAgainstWitness, c.primary)
  228. // We return the error and don't process anymore witnesses
  229. return ErrLightClientAttack
  230. }
  231. // examineConflictingHeaderAgainstTrace takes a trace from one provider and a divergent header that
  232. // it has received from another and preforms verifySkipping at the heights of each of the intermediate
  233. // headers in the trace until it reaches the divergentHeader. 1 of 2 things can happen.
  234. //
  235. // 1. The light client verifies a header that is different to the intermediate header in the trace. This
  236. // is the bifurcation point and the light client can create evidence from it
  237. // 2. The source stops responding, doesn't have the block or sends an invalid header in which case we
  238. // return the error and remove the witness
  239. //
  240. // CONTRACT:
  241. // 1. Trace can not be empty len(trace) > 0
  242. // 2. The last block in the trace can not be of a lower height than the target block
  243. // trace[len(trace)-1].Height >= targetBlock.Height
  244. // 3. The
  245. func (c *Client) examineConflictingHeaderAgainstTrace(
  246. ctx context.Context,
  247. trace []*types.LightBlock,
  248. targetBlock *types.LightBlock,
  249. source provider.Provider, now time.Time,
  250. ) ([]*types.LightBlock, *types.LightBlock, error) {
  251. var (
  252. previouslyVerifiedBlock, sourceBlock *types.LightBlock
  253. sourceTrace []*types.LightBlock
  254. err error
  255. )
  256. if targetBlock.Height < trace[0].Height {
  257. return nil, nil, fmt.Errorf("target block has a height lower than the trusted height (%d < %d)",
  258. targetBlock.Height, trace[0].Height)
  259. }
  260. for idx, traceBlock := range trace {
  261. // this case only happens in a forward lunatic attack. We treat the block with the
  262. // height directly after the targetBlock as the divergent block
  263. if traceBlock.Height > targetBlock.Height {
  264. // sanity check that the time of the traceBlock is indeed less than that of the targetBlock. If the trace
  265. // was correctly verified we should expect monotonically increasing time. This means that if the block at
  266. // the end of the trace has a lesser time than the target block then all blocks in the trace should have a
  267. // lesser time
  268. if traceBlock.Time.After(targetBlock.Time) {
  269. return nil, nil,
  270. errors.New("sanity check failed: expected traceblock to have a lesser time than the target block")
  271. }
  272. // before sending back the divergent block and trace we need to ensure we have verified
  273. // the final gap between the previouslyVerifiedBlock and the targetBlock
  274. if previouslyVerifiedBlock.Height != targetBlock.Height {
  275. sourceTrace, err = c.verifySkipping(ctx, source, previouslyVerifiedBlock, targetBlock, now)
  276. if err != nil {
  277. return nil, nil, fmt.Errorf("verifySkipping of conflicting header failed: %w", err)
  278. }
  279. }
  280. return sourceTrace, traceBlock, nil
  281. }
  282. // get the corresponding block from the source to verify and match up against the traceBlock
  283. if traceBlock.Height == targetBlock.Height {
  284. sourceBlock = targetBlock
  285. } else {
  286. sourceBlock, err = source.LightBlock(ctx, traceBlock.Height)
  287. if err != nil {
  288. return nil, nil, fmt.Errorf("failed to examine trace: %w", err)
  289. }
  290. }
  291. // The first block in the trace MUST be the same to the light block that the source produces
  292. // else we cannot continue with verification.
  293. if idx == 0 {
  294. if shash, thash := sourceBlock.Hash(), traceBlock.Hash(); !bytes.Equal(shash, thash) {
  295. return nil, nil, fmt.Errorf("trusted block is different to the source's first block (%X = %X)",
  296. thash, shash)
  297. }
  298. previouslyVerifiedBlock = sourceBlock
  299. continue
  300. }
  301. // we check that the source provider can verify a block at the same height of the
  302. // intermediate height
  303. sourceTrace, err = c.verifySkipping(ctx, source, previouslyVerifiedBlock, sourceBlock, now)
  304. if err != nil {
  305. return nil, nil, fmt.Errorf("verifySkipping of conflicting header failed: %w", err)
  306. }
  307. // check if the headers verified by the source has diverged from the trace
  308. if shash, thash := sourceBlock.Hash(), traceBlock.Hash(); !bytes.Equal(shash, thash) {
  309. // Bifurcation point found!
  310. return sourceTrace, traceBlock, nil
  311. }
  312. // headers are still the same. update the previouslyVerifiedBlock
  313. previouslyVerifiedBlock = sourceBlock
  314. }
  315. // We have reached the end of the trace. This should never happen. This can only happen if one of the stated
  316. // prerequisites to this function were not met. Namely that either trace[len(trace)-1].Height < targetBlock.Height
  317. // or that trace[i].Hash() != targetBlock.Hash()
  318. return nil, nil, errNoDivergence
  319. }
  320. // getTargetBlockOrLatest gets the latest height, if it is greater than the target height then it queries
  321. // the target heght else it returns the latest. returns true if it successfully managed to acquire the target
  322. // height.
  323. func (c *Client) getTargetBlockOrLatest(
  324. ctx context.Context,
  325. height int64,
  326. witness provider.Provider,
  327. ) (bool, *types.LightBlock, error) {
  328. lightBlock, err := witness.LightBlock(ctx, 0)
  329. if err != nil {
  330. return false, nil, err
  331. }
  332. if lightBlock.Height == height {
  333. // the witness has caught up to the height of the provider's signed header. We
  334. // can resume with checking the hashes.
  335. return true, lightBlock, nil
  336. }
  337. if lightBlock.Height > height {
  338. // the witness has caught up. We recursively call the function again. However in order
  339. // to avoud a wild goose chase where the witness sends us one header below and one header
  340. // above the height we set a timeout to the context
  341. lightBlock, err := witness.LightBlock(ctx, height)
  342. return true, lightBlock, err
  343. }
  344. return false, lightBlock, nil
  345. }
  346. // newLightClientAttackEvidence determines the type of attack and then forms the evidence filling out
  347. // all the fields such that it is ready to be sent to a full node.
  348. func newLightClientAttackEvidence(conflicted, trusted, common *types.LightBlock) *types.LightClientAttackEvidence {
  349. ev := &types.LightClientAttackEvidence{ConflictingBlock: conflicted}
  350. // if this is an equivocation or amnesia attack, i.e. the validator sets are the same, then we
  351. // return the height of the conflicting block else if it is a lunatic attack and the validator sets
  352. // are not the same then we send the height of the common header.
  353. if ev.ConflictingHeaderIsInvalid(trusted.Header) {
  354. ev.CommonHeight = common.Height
  355. ev.Timestamp = common.Time
  356. ev.TotalVotingPower = common.ValidatorSet.TotalVotingPower()
  357. } else {
  358. ev.CommonHeight = trusted.Height
  359. ev.Timestamp = trusted.Time
  360. ev.TotalVotingPower = trusted.ValidatorSet.TotalVotingPower()
  361. }
  362. ev.ByzantineValidators = ev.GetByzantineValidators(common.ValidatorSet, trusted.SignedHeader)
  363. return ev
  364. }