Pika Protocol Security Assessment - Amazon AWS

Page created by Darren Chen
 
CONTINUE READING
Security Assessment

Pika Protocol
Jun 14th, 2021
Pika Protocol Security Assessment

Table of Contents
Summary

Overview
 Project Summary
 Audit Summary
 Vulnerability Summary
 Audit Scope

Findings
 PLP-01 : SafeMathUpgradeable Not Used
 PPC-01 : Unhandled Return Value
 PPP-01 : Check-effect-interaction Pattern Violation
 PPP-02 : Lack of Input Validation
 PPP-03 : Missing Emit Events to Setter Functions
 PPP-04 : Centralized Risk
 PPP-05 : Dead Code
 RDP-01 : Centralized Risk
 RDP-02 : Lack of Input Validation
 SPC-01 : Centralized Risk
 SPC-02 : Dead Code
 STW-01 : Lack of Input Validation

Appendix

Disclaimer

About
Pika Protocol Security Assessment

Summary
This report has been prepared for Pika Protocol smart contracts, to discover issues and vulnerabilities in
the source code of their Smart Contract as well as any contract dependencies that were not part of an
officially recognized library. A comprehensive examination has been performed, utilizing Static Analysis and
Manual Review techniques.

The auditing process pays special attention to the following considerations:

      Testing the smart contracts against both common and uncommon attack vectors.
      Assessing the codebase to ensure compliance with current best practices and industry standards.
      Ensuring contract logic meets the specifications and intentions of the client.
      Cross referencing contract structure and implementation against similar smart contracts produced
      by industry leaders.
      Thorough line-by-line manual review of the entire codebase by industry experts.

The security assessment resulted in findings that ranged from critical to informational. We recommend
addressing these findings to ensure a high level of security standards and industry practices. We suggest
recommendations that could better serve the project from the security perspective:

      Enhance general coding practices for better structures of source codes;
      Add enough unit tests to cover the possible use cases given they are currently missing in the
      repository;
      Provide more comments per each function for readability, especially contracts are verified in public;
      Provide more transparency on privileged activities once the protocol is live.
Pika Protocol Security Assessment

Overview
Project Summary

Project Name            Pika Protocol

Platform                Custom

Language                Solidity

Codebase                https://github.com/PikaProtocol/PikaContract/tree/master/contracts

Commit
                        
Audit Summary

Delivery Date           Jun 14, 2021

Audit Methodology       Static Analysis, Manual Review

Key Components

Vulnerability Summary

Total Issues            12

  Critical              0

  Major                 3

  Medium                0

  Minor                 2

  Informational         7

  Discussion            0
Pika Protocol Security Assessment

Audit Scope

ID    file                              SHA256 Checksum

PLP   lib/PerpLib.sol                   4c3eb7b78ff9e1d6e1761ea24c577fafe9b4e886713958f268f450a779010871

PMP   lib/PerpMath.sol                  052c9d2502031ed4e71eaa46d2bdcf3d47eb7e7bbdd70a58a3c317bbfb675a39

UER   lib/UniERC20.sol                  ead6dc4d3b9816c1d9d92705c8bdb4501134b69d5e3c026394aba1b611d423c9

COP   oracle/ChainlinkOracle.sol        a71b9284ceff2b9d32b083f8076f5cffc96e55e1efe17e24cdf2afc19fb1fdb0

IOP   oracle/IOracle.sol                24560493f11391e73962457fd47efd03703411dd16c39c1b9a96fd47f16fdd18

SOP   oracle/SimpleOracle.sol           864073e72a725153ea52bdb6f6fef9f8fba57cb364d1a11cb7152878905309ff

IPP   perp/IPikaPerp.sol                316f743e6d52056165399224586eee621a6c2853b366bd4f2b539f227979c92a

PPP   perp/PikaPerp.sol                 2e1b1809b78243ccaa903313ea9ea355e7814f65b916b7c46bb7407f5d24e795

SPC   staking/Staking.sol               0c7a8a0ba888a45c4d7990cfb1ae3ff07dac2e86f21ef5288bd0a50eea8a6d0b

STW   staking/StakingTokenWrapper.sol   ab23f58ec966d82597f9e0618e1987b65df8ab42d8cab66fa84e594daf70e4e3

IPC   token/IPika.sol                   27f4119fafdfa7e76aeb0dd643cec320980f06fda561955a4a3b3ed4cb4dff5d

IRD   token/IRewardDistributor.sol      318111492b268b20c38e155f33277bec618e1d14bc377c7ec3389655040d0890

PKS   token/PKS.sol                     5e325d0359514c97f15b3833fde40f88a1bf70934789d3be920c4c8b3382232c

PPC   token/Pika.sol                    17cfe46e80c4000237eb489f660819dab672914d6de4904c07dd07f75d142f51

RDP   token/RewardDistributor.sol       3088d30554ec58d2c6f141faaa3993937f30c9ecb71475b50e29b32243a125e9

SER   token/SimpleERC20.sol             8223e67ce62bf8352dc7b7448dab5d691347d9499e9b0148396d5777377f64f0
Pika Protocol Security Assessment

Findings

                                                                   Critical                   0 (0.00%)
                                                                   Major                  3 (25.00%)

                                12                                 Medium
                                                                   Minor
                                                                                              0 (0.00%)
                                                                                          2 (16.67%)
                             Total Issues
                                                                   Informational          7 (58.33%)
                                                                   Discussion                 0 (0.00%)

ID       Title                                     Category                        Severity               Status

PLP-01   SafeMathUpgradeable Not Used              Mathematical Operations           Informational           Resolved

PPC-01   Unhandled Return Value                    Volatile Code                     Informational           Resolved

         Check-effect-interaction Pattern
PPP-01                                             Logical Issue                     Minor                   Resolved
         Violation

PPP-02   Lack of Input Validation                  Volatile Code                     Minor                   Resolved

PPP-03   Missing Emit Events to Setter Functions   Coding Style                      Informational           Acknowledged

                                                   Centralization /
PPP-04   Centralized Risk                                                            Major                   Acknowledged
                                                   Privilege

PPP-05   Dead Code                                 Gas Optimization                  Informational           Resolved

                                                   Centralization /
RDP-01   Centralized Risk                                                            Major                   Acknowledged
                                                   Privilege

                                                                                                             Partially
RDP-02   Lack of Input Validation                  Volatile Code                     Informational
                                                                                                             Resolved

                                                   Centralization /
SPC-01   Centralized Risk                                                            Major                   Acknowledged
                                                   Privilege

SPC-02   Dead Code                                 Gas Optimization                  Informational           Resolved

STW-01   Lack of Input Validation                  Volatile Code                     Informational           Resolved
Pika Protocol Security Assessment

PLP-01 | SafeMathUpgradeable Not Used

 Category                             Severity                 Location                  Status

 Mathematical Operations                Informational          lib/PerpLib.sol: 1            Resolved

Description
The SafeMathUpgradeable library is imported but not used in the arithmetical operations in the contract
PerpLib.sol at all, which will lead to potential overflow/underflow and incorrect results.

Recommendation
We advise the client to adopt the arithmetical methods in SafeMathUpgradeable library to perform any
arithmetical operations in the contract PerpLib.sol

Alleviation
The client heeded our advice and resolved this issue in commit :
abea090f4f9262b9a204149dbf06876d5fb8fd90.
Pika Protocol Security Assessment

PPC-01 | Unhandled Return Value

 Category                Severity                Location                              Status

 Volatile Code              Informational        token/Pika.sol: 122, 129                  Resolved

Description
Return value of function claimRewards() based on interface IRewardDistributor is ignored in function
recoverReward() and claimRewards() .

Recommendation
We advise the client to handle the return value of claimRewards() to check if it's implementation is
executed without any error.

Alleviation
[Pika]: The team reviewed the finding and believe no changes if needed as the value should always be
valid in the returned result.
Pika Protocol Security Assessment

PPP-01 | Check-effect-interaction Pattern Violation

 Category                  Severity          Location                             Status

 Logical Issue               Minor           perp/PikaPerp.sol: 621                  Resolved

Description
The value of pikaReward is updated after token.uniTransfer(rewardDistributor, pikaReward); , which
violates the check-effect-interaction pattern.

Recommendation
We advise the client to revise the function distributeReward() by adopting the nonReentrant modifier
from the Openzeppelin library, or by copying the revised function distributeReward() as follows:

   1 function distributeReward() external override returns (uint256) {
   2   if (pikaReward > 0) {
   3     uint distributedReward = pikaReward;
   4     pikaReward = 0;
   5     token.uniTransfer(rewardDistributor, distributedReward);
   6        emit RewardDistribute(rewardDistributor, distributedReward);
   7        return distributedReward;
   8   }
   9   return 0;
  10 }

Alleviation
The client heeded our advice and resolved this issue in commit :
abea090f4f9262b9a204149dbf06876d5fb8fd90.
Pika Protocol Security Assessment

PPP-02 | Lack of Input Validation

 Category               Severity         Location                                    Status

 Volatile Code            Minor          perp/PikaPerp.sol: 194~196                     Resolved

Description
The assigned values to pika , token and oracle should be verified as non-zero values to prevent being
mistakenly assigned as address(0) in the initialize function.

Recommendation
We advise the client to check that the addresses are not zero by adding the following checks in the
constructor function.

   1 require(_pika != address(0), "_pika is a zero address");
   2 require(address(_token) != address(0), "_token is from a zero address");
   3 require(address(_oracle) != address(0), "_oracle is from a zero address");

Alleviation
The client heeded our advice and resolved this issue in commit :
abea090f4f9262b9a204149dbf06876d5fb8fd90.
Pika Protocol Security Assessment

PPP-03 | Missing Emit Events to Setter Functions

 Category     Severity           Location                                                             Status

 Coding                          perp/PikaPerp.sol: 718, 724, 729, 733, 739, 745, 752, 760, 764, 76
                 Informational                                                                            Acknowledged
 Style                           8, 772, 776

Description
The function that affects the status of sensitive variables should be able to emit events as notifications to
customers and for tracking down the issue and status of the transaction.

         setGuardian()

         setGovernor()

         setRewardDistributor()

         setLiquidity()

         setMarketStatus()

         setParametersPerSec()

         setThresholds()

         setTradingFee()

         setReferrerCommission()

         setPikaRewardRatio()

         setMaxPokeElapsed()

         setDynamicLiquidity()

Recommendation
We advise the client to add events and emit them in each corresponding function, for all the essential state
variables that are possible to be changed during runtime.

Alleviation
[Pika]: The team reviewed the findings and decided not to apply any changes. The team concerned after
adding these events, the contract will exceed the size limit.
Pika Protocol Security Assessment

PPP-04 | Centralized Risk

 Category              Severity    Location                                                        Status

 Centralization /                  perp/PikaPerp.sol: 718, 724, 729, 733, 739, 745, 752, 760, 76
                          Major                                                                        Acknowledged
 Privilege                         4, 768, 772, 776

Description
The account owner of the governor role can update many sensitive variables by calling the functions in
the below list. Any compromise to this account may allow the hacker to take advantage of these functions
to manipulate and control the contract.

       setGuardian()

       setGovernor()

       setRewardDistributor()

       setLiquidity()

       setMarketStatus()

       setParametersPerSec()

       setThresholds()

       setTradingFee()

       setReferrerCommission()

       setPikaRewardRatio()

       setMaxPokeElapsed()

       setDynamicLiquidity()

Recommendation
We advise the client to carefully manage the role governor 's account private key and avoid any potential
risks of being hacked. In general, we strongly recommend centralized privileges or roles in the protocol to
be improved via a decentralized mechanism or via smart-contract-based accounts with enhanced security
practices, f.e. Multisignature wallets.

Indicatively, here are some feasible solutions that would also mitigate the potential risk:

      Time-lock with reasonable latency, i.e. 48 hours, for awareness on privileged operations;
      Assignment of privileged roles to multi-signature wallets to prevent a single point of failure due to the
      private key;
      Introduction of a DAO / governance/voting module to increase transparency and user involvement.
Pika Protocol Security Assessment

Alleviation
[Pika]: The team planned to initially use the timelock contract for governance mechanism and potentially
have a DAO contract be the owner in the long term.

The team plan to use OpenZeppelin's timelock contract:

      https://github.com/OpenZeppelin/openzeppelin-
      contracts/blob/master/contracts/governance/TimelockController.sol

Show less
Pika Protocol Security Assessment

PPP-05 | Dead Code

 Category                 Severity               Location                           Status

 Gas Optimization           Informational        perp/PikaPerp.sol: 150, 152            Resolved

Description
Variables pendingGovernor , pendingGuardian can be removed as they are not used throughout the
codebase.

Alleviation
The client heeded our advice and resolved this issue in commit :
abea090f4f9262b9a204149dbf06876d5fb8fd90.
Pika Protocol Security Assessment

RDP-01 | Centralized Risk

 Category                         Severity     Location                                Status

 Centralization / Privilege          Major     token/RewardDistributor.sol: 110               Acknowledged

Description
The address of pikaPerp can be updated by calling function setPikaPerp() through the account
governor . Any update of address pikaPerp can affect the number of rewards and pending rewards that

are calculated in function updateRewards() and function claimable() .

Recommendation
We advise the client to carefully manage the governor 's account private key and avoid any potential risks
of being hacked. In general, we strongly recommend centralized privileges or roles in the protocol to be
improved via a decentralized mechanism or via smart-contract-based accounts with enhanced security
practices, f.e. Multisignature wallets.

Indicatively, here are some feasible solutions that would also mitigate the potential risk:

      Time-lock with reasonable latency, i.e. 48 hours, for awareness on privileged operations;
      Assignment of privileged roles to multi-signature wallets to prevent single point of failure due to the
      private key;
      Introduction of a DAO / governance / voting module to increase transparency and user involvement.

Alleviation
[Pika]: The team planned to initially use the timelock contract for governance mechanism and potentially
have a DAO contract be the owner in the long term.

The team plan to use OpenZeppelin's timelock contract:

      https://github.com/OpenZeppelin/openzeppelin-
      contracts/blob/master/contracts/governance/TimelockController.sol

Show less
Pika Protocol Security Assessment

RDP-02 | Lack of Input Validation

 Category          Severity              Location                             Status

 Volatile Code        Informational      token/RewardDistributor.sol: 44~45      Partially Resolved

Description
The assigned values to pikaToken and rewardToken in the constructor of RewardDistributor.sol should
be verified as a non-zero value to prevent error.

Recommendation
Check that the passed-in values are non-zero values. Example:

   1 require(_pikaToken != 0, "_pikaToken is a zero value");
   2 require(_rewardToken != 0, "_rewardToken is a zero value");

Alleviation
The client heeded our advice and partially resolved this issue in commit :
abea090f4f9262b9a204149dbf06876d5fb8fd90.
Pika Protocol Security Assessment

SPC-01 | Centralized Risk

 Category                            Severity       Location                         Status

 Centralization / Privilege               Major     staking/Staking.sol: 172            Acknowledged

Description
The owner of the account owner can transfer an arbitrary amount of token to an arbitrary address by
calling function recoverERC20()

Recommendation
We advise the client to carefully manage the owner account's private key and avoid any potential risks of
being hacked. In general, we strongly recommend centralized privileges or roles in the protocol to be
improved via a decentralized mechanism or via smart-contract based accounts with enhanced security
practices, f.e. Multisignature wallets.

Indicatively, here are some feasible solutions that would also mitigate the potential risk:

      Time-lock with reasonable latency, i.e. 48 hours, for awareness on privileged operations;
      Assignment of privileged roles to multi-signature wallets to prevent single point of failure due to the
      private key;
      Introduction of a DAO / governance / voting module to increase transparency and user involvement.

Alleviation
[Pika]: The team planned to make the owner be the timelock contract for further operations.
Pika Protocol Security Assessment

SPC-02 | Dead Code

 Category               Severity              Location                                    Status

 Gas Optimization          Informational      staking/Staking.sol: 177, 228~231              Resolved

Description
The modifier notPaused and function setPaused() are not used by other functionalities throughout the
codebase

Recommendation
We advise the client to remove the modifier notPaused and function setPaused() to save gas, or use it to
control sensitive functions like functions stack() and withdraw() in Synthetix codebase

Alleviation
The client heeded our advice and resolved this issue in commit :
abea090f4f9262b9a204149dbf06876d5fb8fd90.
Pika Protocol Security Assessment

STW-01 | Lack of Input Validation

 Category           Severity              Location                                     Status

 Volatile Code         Informational      staking/StakingTokenWrapper.sol: 22             Resolved

Description
The assigned values to stakingToken in the constructor of StakingTokenWrapper.sol should be verified
as a non-zero value to prevent error.

Recommendation
Check that the passed-in values are non-zero values. Example:

   1 require(_stakingToken != 0, "_stakingToken is a zero value");

Alleviation
The client heeded our advice and resolved this issue in commit :
abea090f4f9262b9a204149dbf06876d5fb8fd90.
Pika Protocol Security Assessment

Appendix
Finding Categories

Centralization / Privilege
Centralization / Privilege findings refer to either feature logic or implementation of components that act
against the nature of decentralization, such as explicit ownership or specialized access roles in
combination with a mechanism to relocate funds.

Gas Optimization
Gas Optimization findings do not affect the functionality of the code but generate different, more optimal
EVM opcodes resulting in a reduction on the total gas cost of a transaction.

Mathematical Operations
Mathematical Operation findings relate to mishandling of math formulas, such as overflows, incorrect
operations etc.

Logical Issue
Logical Issue findings detail a fault in the logic of the linked code, such as an incorrect notion on how
block.timestamp works.

Volatile Code
Volatile Code findings refer to segments of code that behave unexpectedly on certain edge cases that may
result in a vulnerability.

Coding Style
Coding Style findings usually do not affect the generated byte-code but rather comment on how to make
the codebase more legible and, as a result, easily maintainable.

Checksum Calculation Method
The "Checksum" field in the "Audit Scope" section is calculated as the SHA-256 (Secure Hash Algorithm 2
with digest size of 256 bits) digest of the content of each file hosted in the listed source repository under
the specified commit.
Pika Protocol Security Assessment

The result is hexadecimal encoded and is the same as the output of the Linux "sha256sum" command
against the target file.
Pika Protocol Security Assessment

Disclaimer
This report is subject to the terms and conditions (including without limitation, description of services,
confidentiality, disclaimer and limitation of liability) set forth in the Services Agreement, or the scope of
services, and terms and conditions provided to the Company in connection with the Agreement. This
report provided in connection with the Services set forth in the Agreement shall be used by the Company
only to the extent permitted under the terms and conditions set forth in the Agreement. This report may not
be transmitted, disclosed, referred to or relied upon by any person for any purposes without CertiK’s prior
written consent.

This report is not, nor should be considered, an “endorsement” or “disapproval” of any particular project or
team. This report is not, nor should be considered, an indication of the economics or value of any
“product” or “asset” created by any team or project that contracts CertiK to perform a security
assessment. This report does not provide any warranty or guarantee regarding the absolute bug-free
nature of the technology analyzed, nor do they provide any indication of the technologies proprietors,
business, business model or legal compliance.

This report should not be used in any way to make decisions around investment or involvement with any
particular project. This report in no way provides investment advice, nor should be leveraged as investment
advice of any sort. This report represents an extensive assessing process intending to help our customers
increase the quality of their code while reducing the high level of risk presented by cryptographic tokens
and blockchain technology.

Blockchain technology and cryptographic assets present a high level of ongoing risk. CertiK’s position is
that each company and individual are responsible for their own due diligence and continuous security.
CertiK’s goal is to help reduce the attack vectors and the high level of variance associated with utilizing
new and consistently changing technologies, and in no way claims any guarantee of security or
functionality of the technology we agree to analyze.
Pika Protocol Security Assessment

About
Founded in 2017 by leading academics in the field of Computer Science from both Yale and Columbia
University, CertiK is a leading blockchain security company that serves to verify the security and
correctness of smart contracts and blockchain-based protocols. Through the utilization of our world-class
technical expertise, alongside our proprietary, innovative tech, we’re able to support the success of our
clients with best-in-class security, all whilst realizing our overarching vision; provable trust for all
throughout all facets of blockchain.
You can also read