Blockchain security analysis layer by layer
Tags: blockchain, security, bugbounty
Published: 2021-05-06 06:00:00

Hello Everyone, I'm Web application security researcher and full time BugBounty hunter. But, now I'm curious about Blockchain security. So, Now I'm starting deep understanding how DeFi, Smart Contract, Blockchain etc works. If you interested get up-to-date [Latest cryptocurrency security news](https://portswigger.net/daily-swig/cryptocurrency) , worlds largest Crypto Bug Bounty platform is [Immunefi](https://immunefi.com) and See there [Public BugBounty program ](https://immunefi.com/explore/) Bounty available more then $20M. Also, [HATS.FINANCE](https://hats.finance/) another Decentralized smart bug bounty marketplace. The main advantage of this platform Anyone, anywhere can find vulnerabilities and contribute to protocol protection in a fully decentralized manner no KYC required and On-chain bug submission. You can see their active [ Vaults](https://app.hats.finance/vaults) here. So, let's start hacking.      

###Abstract
The current blockchain structure can be roughly divided into application layer, smart contract layer, incentive layer, consensus layer, network layer and data layer from top to bottom. The security analysis of each layer will be performed separately below. This is not technical writing. I'm covering some basic think.

###Application Layer
 Application layer security mainly covers the security issues of centralized nodes such as the exchanges which involve digital currency transactions and manage large amounts of funds. These nodes are at any point of failure of the entire blockchain network, and the attack yield is high and the cost is low, which is the preferred target of the attackers .

Unauthorized Access to An Exchange Server. Exchanges often deposit large amounts of money and are easily targeted. Once the exchange server authority is obtained and the key information is modified, the attacker can steal the funds key, tamper with the transaction amount or leak sensitive information, causing economic and reputational devastating blows to the exchange.

For example, the Youbit (formerly Yapizon) stolen event. On April 22, 2017, 4 hot wallets of Youbit were stolen, lost 3,816 BTC, with a total value of about $5,300,000, accounting for 36% of the exchange’s funds. On December 19, 2017, Youbit announced that it was attacked again, lost approximately 17% of its assets, and at the same time announced the exchange closed and entered the bankruptcy process.

Exchange DDoS. Due to the high demand for network bandwidth in the trading platform, once a DDoS attack occurs, it is very serious for the platform and the entire industry. If the trading platform is attacked by DDoS, not only will itself suffer losses, but the transaction volume of the blockchain currency will also be greatly reduced, which will indirectly affect the rise and fall of the blockchain currency .

According to the report of global DDoS threat landscape Q3 2017 by Incapsula [16], although its industry scale is still relatively small, Bitcoin has become one of the top 10 industries which are most vulnerable to DDoS attacks. This reflects to a certain extent that the entire blockchain industry is facing serious DDoS security challenges. For example, from November 2017 to December 2017 Bitfinex announced that it had suffered the DDoS attack for three times, and all the services of the exchange had been shut down for a long time [17]. The attacker creates pressure on the server by creating a large number of empty accounts, causing related services and APIs to go offline for hours.

Employees Host Security. On June 20, 2011, the large Bitcoin exchange Mt.Gox was attacked. Its server was not compromised, but the attacker gained access to a computer used by an auditor of Mt.Gox, and got a read-only database file, resulting in about 60000 users’ username, email address, and encrypted password [18] to be leaked. After obtaining this sensitive information, the attacker cracked the password of one of the large accounts, issued a large sales message through this account, and sold 400,000 BTC [19] under it, trying to transfer funds through the legal transaction process. Fortunately, because the exchange protection measures are effective, it limits the maximum value of $1,000 BTC per account per day, so it does not cause much damage to this account. However, a large number of BTC sale requests caused the exchange BTC price to drop to 1 cent, resulting in an impact of approximately $8,750,000 in assets.

Malicious Program Infection. Once a malicious program is implanted into the exchange system, it is likely to cause a large amount of sensitive information leakage, including key and wallet files. The key is everything, and the leakage of sensitive information often means losing control of all assets. The exchange Mt.Gox was attacked in 2014. The key file of Mt.Gox was stored locally in clear text, and the key file wallet.dat leaked due to Trojan infection, resulting in a large amount of asset loss and eventually, Mt.Gox went bankruptcy [20]. It is worth noting that in this attack, the attacker used two years to gradually transfer assets in order to avoid the community recovering the loss through hard forks. The emergence of this type of APT attack means that monitoring of the threat of attack in the blockchain industry cannot rely solely on short-term anomaly transaction monitoring.

Initial Coin Offering. Tampering Attack: When ICO raises funds, it usually hangs the receiving address on the project official website, and then the investor will transfer money to this address for the corresponding token. Hackers can tamper with the collection address through attacks such as domain hijacking, web vulnerabilities, or social engineering.

Phishing attack: The attacker uses social engineering and other means to impersonate the official, allowing the user to transfer money to the attacker’s wallet address. For example, an attacker can use an approximate domain name and highly phishing website to defraud investors or use email to disseminate fake information, such as ICO project’s payment address change notice, etc. or disseminate phishing information on social software and media to defraud investors.

Mining Machine System. The cyber security awareness of mining device manufacturers is uneven, and because of its closed source characteristics, the security of its code cannot be checked by the public. Once a cyber security issue occurs, the result is fatal. And whether the device manufacturer will intersperse the back door for remote control of the device, or steal the mining output, is still remain to be discussed.

0day: Most mining system is a general-purpose system. Once a mining system is found to have a 0 day vulnerability, the security barriers of the system will be broken in an instant. The attacker can use the vulnerability to obtain the modify permission and then tamper with reward receiving address and then hijack the user’s reward.

Weak password attack: At present, the mining system in the market is based on the B/S architecture. Access to the mining system is usually through the web or other means. If the weak password is used, it will be vulnerable to intrusion.

Mining Pool. By June 2018, the top five Bitcoin mining pools in the world are BTC.com, AntPool, SlushPool, BTC.TOP and F2Pool. About 60% of the world’s hash power is in the hands of Chinese miners [21].

Hash power forgery attack: The mining pool will test the actual hash power of the current miner through a certain proof of work test algorithm. The hacker can falsely report the hash power by finding the vulnerability of the algorithm, and then obtain the excessive reward that doesn’t match the actual contribution.

Selfish mining attack: A malicious mining pool decides not to release the block it finds, and thus creates a fork. When the private fork is longer than the public chain, the malicious mining pool issues the private fork. Because the fork is the longest chain in the current network, it will be recognized as a legal chain by honest miners, so the original public chain and the honest data it contains will be discarded. The results of the study indicate that the malicious mining pools will yield more benefits normally by using selfish mining strategies. But such attacks usually require huge hash power as a support.

Centralization: The existence of the mining pool violates the principle of decentralization of the blockchain. Theoretically, if it can control at least 51% of the hash power of entire network, it will be able to monopolize the mining right, billing right and distribution right, which will affect the ecological security of the blockchain, so that the credit system of the cryptocurrency will cease to exist and the cryptocurrency system will be completely destroyed.

Possible Methods. It is impossible for any one party to respond to various attacks at the application layer. The application developers should ensure that the softwares don’t contain discovered vulnerabilities and are thoroughly tested. As the central node, such as a trading platform, real-time monitoring of system health and some protected methods (e.g. data encryption storage, etc.) are required to ensure that the system is not subject to internal and external attacks. All employees should be systematically trained before they are employed to avoid becoming an attack portal. As a user, you should be able to keep your own account and key properly, distinguish between true and false information and be cautious in trading to avoid phishing attacks.

###Smart Contract Layer
 A smart contract is more than just a computer program that can be executed automatically. It is a system participant. It responds to the received message, it can receive and store value, and it can send out information and value [22]. For the security risks of smart contracts, the following attacks are summarized.
Reentrancy Attack. The essence of reentrancy attack is to hijack the contract control flow and destroy the atomicity of the transaction, which can be understood as a logical race condition problem. For example, The DAO was attacked, and the attacker used the vulnerability in the contract to launch a reentrancy attack and gained 60 million dollars. In order to recover this part of the funds, the Ethereum community decided to perform a hard fork, roll back all the transaction records since the start of the attack and fix the contract vulnerabilities in the new branch. The vulnerability is described below. Here is a simplified version of The DAO contract:

```
contract SimpleDAO {
mapping (address => uint) public credit; 
function donate(address to){credit [to]+= msg.value;
  }
 function queryCredit(address to) returns (uint){
   return credit [];
}
function withdraw(uint amount) {
    if (credit [msg.sender]>= amount){
    credit[ msg.sender]-= amount ; 
   }
  }
}

```

Participants call the donate function to donate their own Ether to a contract address, the donation information is stored in the credit array, and the recipient contract calls The DAO’s withdraw function to receive funds. Before actually sending the transaction, The DAO checks if there is enough donation in the credit array, and after the transaction is over, the transaction amount is reduced from credit.
The attacker first constructs a malicious contract Mallory, as follows: 
```
contract Mollory {
SimpleDao Public dao = SimpleDAO(0x354);
address owner;
function Mallory(){owner = msg.sender;
 }
function getJackpot(){ owner.send(this.balance); 
 }
}

```

After Mallory deployed, the attacker calls The DAO’s donate function to donate a bit of Ether to the Mallory contract. After triggering Mallory’s fallback function (unnamed function), there are many trigger methods, such as transfer money to Mallory. The fallback function will call The DAO’s withdraw function and extract all the funds that belong to it. It seems to be no problem so far. However, after msg.sender.call.value(amount)() in the withdraw is executed, Mallory’s fallback function is automatically called after the transfer is completed due to the transfer operation feature, so the withdraw function is called again. Because credit is not updated at this time, so you can still withdraw money normally, then you fall into a recursive loop, and each time you can extract a part of Ether in the DAO to the Mallory contract.

This loop will continue until one of three conditions occurs, gas is exhausted, the call stack is full, and The DAO balance is insufficient. An exception is thrown when one of the above conditions occurs. Due to the characteristics of the Solidity exception handling, all previous transactions are valid. Theoretically, repeating this operation can extract all the Ether of The DAO’s to Mallory.

Unauthorized Access Attack. Most of this attack due to failure to make explicit function visibility, or fails to do sufficient permission checks, which can cause an attacker to access or modify a function or variable that should not be accessed.

For example, a multi-signature contract vulnerability in the Parity wallet was exploited by an attacker to steal a total of 153,037 Ether in three times. Then Parity official blog and Twitter released security alert [23] and updated the new version of the library contract. The bug comes from the Multi-Sig library file enhanced-wallet.sol written by Parity’s founder Gavin Wood. The attacker exploited the bug to reset the wallet owner, took over the wallet and stolen all the funds. This is essentially a breach of authority in the contract.

Solidity Development Security. Possible bugs when writing smart contracts include:

Race condition: The biggest risk of calling an external function is that the calling behavior may cause the control flow to be hijacked and accidentally modify the contract data. This type of bug has many specific forms, such as reentrant and cross-function race conditions.

Transaction-Ordering Dependence: A attacker can construct his own transaction based on the order information contained in the pending transactions, and try to get his transaction to be written into the block before others.

Integer overflow and underflow: When programming, you should think about whether integer overflows can occur, how the state of uint variables will be transferred, and who has the authority to modify those variables.

Denial of Service Attack Based on Exception Rollback: For example, a crowdfunding contract gives a refund to a participant. The contract may need to traverse an array to process a refund for a group of users. The simple idea is that every refund is successful, otherwise the program should be rolled back. The consequence of this practice is that one of the malicious users forced the refund to fail and all users were unable to receive the refund. It is recommended to use a pull payment mechanism, which separates the refund operation into an independent function, which is called by the refund recipient to pull the refund.

Possible Methods. Once a smart contract is deployed in a distributed, decentralized network, it is difficult to change. It prevents data manipulation and establishes a trust mechanism based on the encryption algorithm. On the other hand, when the blockchain is facing a security attack, it lacks an effective correction mechanism and is difficult to reverse. Therefore, before the development of smart contracts, it is necessary to guard against the vulnerabilities that have already occurred. It should conduct sufficient security tests before issued. Professionals perform code optimizations in a timely manner, conduct regular code audits, and monitor abnormal behavior of deployed contracts to reduce losses. Learn more about [Immunefi learn](https://immunefi.com/learn/). 


###Incentive Layer
 The purpose of the incentive layer is to provide certain incentives to encourage nodes to participate in the security verification of the blockchain. The security of the blockchain depends on the participation of many nodes. For example, the security of the Bitcoin blockchain is based on the great hash power that many nodes participate in the proof of work which makes it impossible for an attacker to provide a higher amount of computation. The verification process of a node usually consumes computing resources and electric power. In order to encourage node participation, the blockchain usually rewards participants in the form of virtual currency. Bitcoin, Litecoin, and Ether are all products of this mechanism.

Blockchain projects need to adapt to the market to automatically adjust the rewards, rather than simply reducing them. In the blockchain project reward mechanism, when the node’s working cost is close to or greater than the income, they often choose not to work for this blockchain, which can easily lead to centralization problems.


###Network Layer
 The information transmission of the blockchain mainly depends on the peer-to-peer network. The P2P network relies on nearby nodes for information transmission in which it must expose each other’s IP. If there is an attacker in the network, it is very easy to bring security threats to other nodes. The node of the public blockchain network may be an ordinary home PC, a cloud server, etc., and its security must be uneven. There must be a node with poor security, and attacking it will directly threaten the other nodes. The main attacks are as follows.

Eclipse attack: The node is kept in an isolated network by hoarding and occupying the victim’s slots. This type of attack is designed to block the latest blockchain information from entering the eclipse node, thereby isolating the nodes [24].

BGP hijacking: At present, the security researchers have proved the conceptual feasibility of the attack. From November 5, 2015, to November 15, 2016, through the analysis and statistics of the node network, most of the bitcoin nodes are currently hosted in a few specific Internet Service Providers (ISP), while 60% of Bitcoin connections are in these ISPs. Therefore, these ISPs can see 60% of Bitcoin traffic, and can also control the traffic of the current Bitcoin network. The researchers verified that at least two attacks are conceptual feasible through the hijacking scenario, and given validation code [25].

The security defense for the network layer can be mainly improved from two aspects: P2P network security and network authentication mechanism. In the transmission process of the network, a reliable encryption algorithm is used for transmission to prevent malicious attackers from stealing or hijacking the node network. Strengthen the validity, rationality and security of data transmission in network. Client nodes should do the necessary verification for important operations and information.


###Data Layer

Block Data. Malicious information attack: Write malicious information, such as virus signatures, politically sensitive topics, etc. in the blockchain. With the data undelete feature of the blockchain, information is difficult to delete after it is written in the blockchain. If malicious information appears in the blockchain, it will be subject to many problems.

A team of researchers at the RWTH Aachen University and the Goethe University Frankfurt in Germany pointed out that among the 1,600 documents added to the Bitcoin blockchain, 59 files contained links to illegal children’s pictures, politically sensitive content or privacy violations [26]. Currently, only a few Bitcoin blockchain transactions contain other data. In the Bitcoin blockchain, about 1.4% of the 251 million transactions contain other data, that is, only a few of these transactions contain illegal or undesirable content [26]. Still, even such small amounts of illegal or inappropriate content can put participants at risk.

Signature and Encryption Method. Cryptography is the key to ensure the security and tamper resistance of blockchain, and blockchain technology relies heavily on the research results of cryptography, which provides a key guarantee for the information integrity, authentication and non-repudiation of the blockchain.

As a mainstay of the blockchain, the encryption technology is particularly important. For example, the MD5 and SHA1 hash algorithms popular in previous years but have been proved to be insufficiently secure. At present, the SHA256 algorithm is widely used in bitcoin. So far, this algorithm is still safe, but with the development of new technology and research, it may not be safe in the future. Therefore, when designing blockchain applications, it is important to carefully choose the encryption method. Current mainstream signature methods include aggregate signature, group signature, ring signature, blind signature, proxy signature, interactive incontestable signature (IIS), blinded verifiable encrypted signature (BVES), and so on.

Attacks on cryptographic algorithms, especially the hash functions, include brute-force attack, collision attack, length expansion attack, back door attack and quantum attack.




Thanks 
[Tamjidur Rohamn](https://twitter.com/tamjid0x01)