<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <channel>
        <title>DeFi (in)security</title>
        <link>https://paragraph.com/@defi-in-security</link>
        <description>DeFi - alternative modern financial system based on new technology principles.</description>
        <lastBuildDate>Sun, 29 Nov 2026 14:02:39 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <language>en</language>
        <image>
            <title>DeFi (in)security</title>
            <url>https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/8671119b664d40e3d460907e2a064dd54a3a11333e417dea1225a5a5ca5e68ad.jpg</url>
            <link>https://paragraph.com/@defi-in-security</link>
        </image>
        <copyright>All rights reserved</copyright>
        <item>
            <title><![CDATA[Runbooks, DR-учения и RTO/RPO: почему DevSecOps-инженер — это не только про пайплайны]]></title>
            <link>https://paragraph.com/@defi-in-security/runbooks-dr-ucheniya-i-rtorpo-pochemu-devsecops-inzhener-—-eto-ne-tolko-pro-pajplajny</link>
            <guid>3vVgfheITUsM7RWfzjHn</guid>
            <pubDate>Sun, 22 Mar 2026 20:32:59 GMT</pubDate>
            <description><![CDATA[Но есть менее заметная, при этом критически важная часть работы — операционная устойчивость. Речь о runbooks, учениях по аварийному восстановлению (DR) и постоянной работе над метриками RTO/RPO. Хочу поделиться практическим взглядом на эту тему.Runbooks: не документация ради документацииRunbook — это не README и не wiki-страница, которую написали год назад и забыли. Это исполняемый регламент: чёткая последовательность действий при конкретном инциденте, написанная так, чтобы её мог выполнить д...]]></description>
            <content:encoded><![CDATA[<p>Но есть менее заметная, при этом критически важная часть работы — операционная устойчивость. Речь о runbooks, учениях по аварийному восстановлению (DR) и постоянной работе над метриками RTO/RPO.</p><p>Хочу поделиться практическим взглядом на эту тему.</p><hr><h3 id="h-runbooks-ne-dokumentaciya-radi-dokumentacii" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Runbooks: не документация ради документации</h3><p>Runbook — это не README и не wiki-страница, которую написали год назад и забыли. Это исполняемый регламент: чёткая последовательность действий при конкретном инциденте, написанная так, чтобы её мог выполнить дежурный инженер в три часа ночи.</p><p>Что отличает хороший runbook:</p><p>Контекст на старте. Не «перезапустите сервис», а «если метрика X превысила порог Y в течение Z минут, и при этом dashboard показывает аномалию на таком-то графике — выполните следующее». Инженер должен за 30 секунд понять: это мой случай или нет.</p><p>Конкретные команды, а не абстракции. Вместо «проверьте состояние кластера» — точная команда с ожидаемым выводом. Runbook не место для творчества — это место для предсказуемости.</p><p>Точки принятия решений. «Если после шага 3 проблема не решена — эскалируйте на L3 через канал #incident-war-room». Дерево решений важнее линейного списка шагов.</p><p>Владелец и дата ревизии. Runbook без владельца — мёртвый runbook. Без регулярного review он устаревает за квартал.</p><p>С позиции DevSecOps я интегрирую в runbooks проверки безопасности: верификацию целостности бэкапов, контроль секретов при failover, валидацию сетевых политик после переключения. Аварийное восстановление не должно открывать дыры в периметре.</p><hr><h3 id="h-dr-ucheniya-myshcy-kotorye-atrofiruyutsya-bez-trenirovok" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">DR-учения: мышцы, которые атрофируются без тренировок</h3><p>Иметь DR-план и никогда его не тестировать — примерно то же самое, что иметь огнетушитель с истёкшим сроком годности. Формально он есть, практически — бесполезен.</p><p>Что я вынес из участия в DR-учениях:</p><p>Первое учение всегда проваливается. И это нормально. Документация не совпадает с реальностью, доступы протухли, DNS-записи указывают не туда. Ценность первого прогона — в списке проблем, которые вы не знали.</p><p>Учения нужно усложнять постепенно. Начинаем с tabletop — проговариваем сценарий за столом. Потом switchover на staging. Потом — контролируемый failover на production с откатом. Потом — Chaos Engineering: отказ приходит без предупреждения.</p><p>Фиксируйте всё. Время каждого шага, кто какое решение принял, где застряли. Без метрик нет улучшений.</p><p>Безопасность во время DR — отдельный чеклист. При переключении на резервную площадку легко «временно» ослабить firewall-правила, забыть про mTLS или использовать shared credentials. DevSecOps-инженер в DR-учении следит, чтобы экстренность не стала оправданием для компромиссов.</p><hr><h3 id="h-rto-i-rpo-metriki-kotorye-opredelyayut-biznes-prioritety" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">RTO и RPO: метрики, которые определяют бизнес-приоритеты</h3><p>Для тех, кто не погружён в тему: — RTO (Recovery Time Objective) — за какое время мы обязаны восстановить сервис. — RPO (Recovery Point Objective) — сколько данных мы можем позволить себе потерять.</p><p>Ключевой инсайт: RTO/RPO — это не технические, а бизнес-решения. Инженеры обеспечивают реализацию, но целевые значения диктует бизнес.</p><p>Как DevSecOps-инженер влияет на улучшение этих метрик:</p><p>Автоматизация failover. Ручное переключение — это всегда +15–30 минут к RTO. Автоматический failover с health-check'ами и canary-проверками сокращает время до минут или секунд.</p><p>Непрерывная репликация вместо периодических бэкапов. RPO в 24 часа — это позавчерашний подход. Стриминговая репликация, CDC (Change Data Capture) и immutable backups позволяют снизить RPO до минут.</p><p>Infrastructure as Code для DR-площадки. Если резервная инфраструктура описана в Terraform/Pulumi и разворачивается автоматически, вы не зависите от «того одного инженера, который знает, как всё настроить».</p><p>Мониторинг самого DR. Репликация может молча сломаться. Бэкапы могут не проходить валидацию. Я настраиваю алерты не только на production, но и на здоровье DR-инфраструктуры.</p><hr><h3 id="h-chto-ya-rekomenduyu-komandam" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Что я рекомендую командам</h3><p>Проведите аудит текущих runbooks. Если дежурный не может выполнить runbook без звонка автору — runbook не работает.</p><p>Запланируйте первое DR-учение. Пусть оно будет простым — tabletop на 2 часа. Главное — начать.</p><p>Задайте бизнесу вопрос: «Какой простой и какая потеря данных для нас допустимы?» Ответ определит ваши инвестиции в инфраструктуру.</p><p>Включите безопасность в DR-процесс с первого дня. Восстановление, которое оставляет систему уязвимой — это не восстановление.</p><hr><p>Операционная устойчивость — это не glamorous-часть DevSecOps. Здесь нет модных инструментов и красивых дашбордов. Но когда наступает реальный инцидент, именно runbooks, отработанные DR-процедуры и выверенные RTO/RPO отделяют управляемый кризис от катастрофы.</p><p>Расскажите в комментариях: как часто ваша команда проводит DR-учения? И есть ли у вас runbooks, которым вы действительно доверяете?</p><hr><p>#DevSecOps #DisasterRecovery #Runbooks #RTO #RPO #SRE #IncidentManagement #CloudSecurity #InfrastructureAsCode #Resilience</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
            <category>devsecops</category>
            <category>dr</category>
            <category>rto</category>
            <category>rpo</category>
            <category>chaosengineering</category>
            <category>iac</category>
            <category>cloudsecurity</category>
            <category>runbooks</category>
            <category>resilience</category>
            <category>sre</category>
            <category>incidentmanagement</category>
            <enclosure url="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/a74c34f1bdb5b8ae4d2096ad4add3999fdd5d51c78d790a34f2ff3a1bed6a887.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Your Code Audit Passed. You Still Got Hacked. Three Times.]]></title>
            <link>https://paragraph.com/@defi-in-security/your-code-audit-passed-you-still-got-hacked-three-times</link>
            <guid>ClY7hq4KN4drhtFoq1Zi</guid>
            <pubDate>Sun, 22 Mar 2026 18:37:31 GMT</pubDate>
            <description><![CDATA[Three DeFi hacks show the same flaw: audits passed, security failed. Prisma, Zunami, and Resolv lost millions due to keys, design, and ops—not code bugs.]]></description>
            <content:encoded><![CDATA[<p>Between 2024 and 2026, three stablecoin protocols tied to the Curve Finance ecosystem were exploited in ways that had nothing to do with the quality of their smart contract audits. Prisma Finance lost $12 million through a peripheral migration contract. Zunami Protocol lost $500K when someone called a function named withdrawStuckToken() with the deployer key. Resolv Labs had $80 million in unbacked USR minted because a single off-chain signer had unlimited power with zero on-chain guardrails.</p><p>All three protocols had been audited. All three audits covered the core contracts. All three got hacked through something that was either out of scope, an architectural assumption, or an operational security failure. The code was fine. The security was not.</p><p>If you manage a DeFi team, run DevSecOps, or are responsible for the security posture of anything that holds other people's money, this article is for you. Three protocols, three hacks, one lesson: audits are necessary but nowhere near sufficient. You need security people, not just security reports.</p><h3 id="h-three-hacks-one-table" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0"><strong>Three Hacks, One Table</strong></h3><figure float="none" data-type="figure" class="img-center"><img src="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/5d349f369a2c03967837749297bfb10599f9810a308b0ad63307b6411a569bdf.png" blurdataurl="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAASCAIAAAC1qksFAAAACXBIWXMAAAsTAAALEwEAmpwYAAAFXUlEQVR4nF1VXUwUVxSel20f1EFtrpULdjAZawfUQWBY9rIPs9BckLuIswtDwV3+BlpHZMNPRnYdQcemDqSurWYkOkbBWrORCqSu8YcH3TQQ7QMP6ktDTGrsg2naxJom9bWZnWRD+z3e3HPuOef7zncpj8cD/wsAwMFIxDTNeCIxM/OdZV0AWRBCksmkYRjJZDKdTmOMaZrORTEME08k4onE3NxcW2srTdPbPtoGIaQMw2BZlmGY3FWapvsP99u2fXX6iiRJglAJIczL2xiNRqcsyzTNmkAAIfS/KAgLTHPCyl4ocJKsBwAwDEONj41/uGXL2loAABjXHTvmlIPrMUVR7mFNoMYwjHgiXofxgQP7P96xg6ZpALa4UVvz8xVFSYwmVAeHe3q6GxrqAQCUqqoIIb/fz7Js7oHyiopoNBpuaQk1h3ieZxgGAMDzvKqqznkoPDI0RAgpKy1bG4Ux7lOUzo6O4ZHhmIOBnZ/spPp6+wzDsCyL53m3KZqmR7TRe/fvXb9xfWVlxbZtCOF7772vKMrTZ08zmczjx48/P3RIVdWx48e9ld5169e5ganUbCbz8OcnT86d/6axqalfVRubmiiEkJAFQihXC0Io3NIS3B+sw3hvaene0lKO48orKsItLbIst0faBUEoKS7ms0AIeSsdngghuB4TQiRJ4jiO5/ntRUWUZVnnzp/7+swZ0zRzJJvmxNu/366u/vL9jRurqy8mJyYR8sVisXf/vFtdffHbq1edHR2x2ICmaV3dXbHYQJ+iQAjv3rn7+vXrpeVlTdPaPmuLxWI1gQDl9/sRQhhjd9AQwvz8rYIgYIy9lV5CCEJIFEWGKeI4ThCEQG1tVlpCRUX53tJStwmO4xiG4XleEARRFHfv2SMIQpXPV1Jc4shU1/WLly4JgkBRlMvB5MTky5e/plKzf715oyiKpmkIoYORSDqdvjp9pa21taunJxJpb2ttPTJwZHBwuKenm2V3zM3Np1Kp1dUXf/z5uyzLwyMjDQ31DgfZInZjjGVZ3pSXByHctWcXxrgxGKyu9lNZ0DTN8zwhxFvprfL5/NXV3kovQmjdhg3uBQhhlc8nSZLDBMZZUn0cx1HpdPrho0fPnz9byUKSpE0bN7VH2pPJZCo1++WpU6IoYozdTbZte3xs3Lbt69euzWQRDoWyGesghKqqWpblbvv09LRtX8QYOw8sLi6aptnZ0RFPxA8d+gIAUFZe5ggpFKoJBCRJkmUZACBJkm3buq4PDg6LYkAURbdeV1oAgKHBoW/PntV1fXJiIpk803+43+PxUDMzM4uLi5qmOVtHUa41udqt/dThsyZQ4yqdEGKaZjKZjMViCKHGYGNDQ73bnyiKHMepqqrrumEYidFR0zR1XXc4kCSps6NzcHBYEATXswAAoii6A+3s6GwMBl11CYIgy81tra0NDfWEkGgWkUi7LDcTQjiOM4wTd+7dVZRef3V1qDmEMQ41hyhZbu7q7grU1rpZclbhbNm+fQghd2sAABxXjBCq8vkIIcH9QVe+HMf5q6txPWZZVpblyYnT4VDYbSscCjlm15dVYTQaXeumR4/Gl5aXVFVtDAb7evtKiotpmlZVdWF+fm5u7oebN5eWl3+8ffvBg/tTF6YW5hcymZ8IIYZhZDKZhfn5TObhrdlbfYrC87wzdFeFa7+EwoJClmU3f7CZpmmXFZqmFaXXMAzXohmG4TiOZVl3xbYXbWcYJmvg25gsIIQej2drfj5l2/bly5enLMuyzudGFI1GNU07fforjHFhQaF7KIoBTdNOnDyp62Ox2ID7C+UAITSMU4qixBNxXR9zPVQQhH8BTi8ab6jxvJ0AAAAASUVORK5CYII=" nextheight="801" nextwidth="1442" class="image-node embed"><figcaption htmlattributes="[object Object]" class="hide-figcaption"></figcaption></figure><br><h3 id="h-what-actually-happened-in-each-case" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0"><strong>What Actually Happened in Each Case</strong></h3><p><strong>Prisma Finance — The Forgotten Helper Contract</strong></p><p>Prisma's core codebase was forked from Liquity, one of the most reviewed and battle-tested protocols in DeFi. The core contracts were immutable and had been through multiple audits. Then the team deployed MigrateTroveZap — a utility contract designed to help users migrate their positions (troves) from one trove manager to another using flash loans. This contract had delegation approval over users' troves. It accepted arbitrary flashloan callbacks. And it had no input validation on collateral parameters. The root cause was twofold: by directly calling the flashloan() function, an attacker could manipulate other Trove Managers' positions, and the contract allowed a mismatch between collateral in the initial position and the new position. The attacker exploited both, opened a small trove, migrated it through MigrateTroveZap to inherit the remainder of wstETH in the contract, and walked away with 1,282 wstETH. This contract was almost certainly not in the main audit scope. It was a convenience wrapper. It felt too simple to warrant a separate engagement. But it had the keys to the kingdom.</p><p><strong>Zunami Protocol — The Admin Key That Shouldn't Have Existed</strong></p><p>Zunami's story is darker. The protocol had been hacked three times before — in 2023 alone, a sandwich attack ($49K), a flash loan price manipulation ($260K), and another flash loan attack on Curve pools ($2.1M). Each time, the team promised fixes and better security. Zunami V2 was launched with audits from Nomoi and PeckShield, and the team explicitly stated that "the primary objective of V2 is to ensure security."</p><p>Then in May 2025, someone used the Zunami Protocol Deployer Wallet to call withdrawStuckToken() on the UsdtCrvUsdStakeDaoCurve strategy contract. That single function call transferred 296,456 LP tokens — the collateral backing zunUSD and zunETH — straight to the attacker's address. No flash loans, no price manipulation, no clever exploit mechanics. Just an admin call from a privileged key.</p><p>Curve Finance founder Michael Egorov commented: "What is worse, admin key existed!" And he was right. The fundamental question isn't whether the deployer key was compromised or whether it was an insider job (the team says they're "considering both scenarios"). The question is why a single EOA had the power to drain all user collateral with one function call, and why nobody flagged this as an unacceptable risk. The protocol's GitHub had no commits for three months before the hack. The domain had expired. Curve gauge rewards dropped to zero right before the exploit. Whether this was a compromise or a rug, the architecture made it trivially easy.</p><p><strong>Resolv Labs — The Unlimited Money Printer</strong></p><p>Resolv's USR was a yield-bearing stablecoin backed by delta-neutral strategies on ETH. The minting process worked in two steps: a user deposits USDC via a requestSwap function, then an off-chain service with a privileged key (the SERVICE_ROLE) calls completeSwap to decide how much USR to mint. The contract checked the minimum amount but had no maximum. No cap. No ratio to collateral. No oracle validation. Whatever the SERVICE_ROLE key said, that's what got minted.</p><p>The SERVICE_ROLE was a single EOA address. The admin role was a multisig — but the role that actually controlled minting was just one private key. The attacker got that key, deposited $200K across two transactions, and minted 80 million unbacked USR. Dumped it on Curve and other DEXs. USR hit $0.025 on Curve within 17 minutes. The attacker walked away with approximately $25 million in ETH.</p><p>As one security researcher put it: "The contract worked perfectly. That's the scariest part." The code was correct. The design was the vulnerability.</p><h3 id="h-the-common-pattern" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0"><strong>The Common Pattern</strong></h3><p>Look at these three incidents side by side and the pattern is impossible to miss.</p><p>In every case, the core protocol contracts were audited and held up fine. In every case, the exploit came through a component that was either peripheral to the main codebase (Prisma's MigrateTroveZap), an architectural assumption about key security (Zunami's deployer wallet, Resolv's SERVICE_ROLE), or both. In every case, there were no on-chain guardrails to limit the blast radius when the assumption failed. And in every case, nobody on the team appeared to be asking: "What's the worst that can happen if this component is compromised?"</p><p>This is not a code quality problem. This is a security architecture and security operations problem. And it's a problem that code audits, by design, are not meant to solve.</p><h3 id="h-why-code-audits-dont-catch-this" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0"><strong>Why Code Audits Don't Catch This</strong></h3><p>A smart contract audit answers a specific question: "Does this code do what it's supposed to do, and does it have exploitable bugs?" That's a valuable question. But it's not the only question that matters.</p><p>Here's what an audit typically does NOT cover:</p><figure float="none" data-type="figure" class="img-center"><img src="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/8486fa160edd6b920c17a340a35fe0d6ebec0d8e76a66ad50e3961ee8bbea4a7.png" alt="Article content" blurdataurl="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAZCAIAAADfbbvGAAAACXBIWXMAAAsTAAALEwEAmpwYAAAGc0lEQVR4nHVWYWjbZhr2lTtM/jgcNshU3kRQPRNMCcELNcE5PKM5iqfWp3pKwAnK8J1bmboh5lCYIOelc3PeBdV3GlFrrHDaoQRUg1IQRiVoFwSZvaJe53SoYDjKRsdx+zEY24/+HvHXs7McZ17Mx/e+n1697/M87ycXggRQdGxgCBIYWDg8HgoFUXTsjQsXzrhQdAy4wHrw/7/mQpBAtXrbMHTTNCzrsN22ymUOhv3BNy7oumYYLVVVHOe4VFqBIC8M+xEkAMN+kkz3es8Mo2VZpqY1DaNlmkYkMglB0JnXPUmA40maXlyYf5ckL2ezCySZDoWC4fD4lcvvkGSaojLZ7DxBpHA8SRApDHsrFApGo1M0vUSS6Wx2nqYXaXqJphdJ8nI8PhMOjwMLhYKvEvD8VveLx837e6q6q+uaqu7GYtMI8rog1GR5R1FkVd3d2/3EskzbfqTr+zDsx/Gkqu6+v/YHhsm329a9u9vV6qaiyBz3Pqhy2CIIgnh+y7Y7jYaoKLIg3Gk0RFneuXTpTY5bk+VGpbLB81vN+3uKIktSXVV3MSzh9Y5CkO/8eQiCfBAE/XfhO/P0kwQw7BeEmihugzOn42DYP9gB5vX+euACdnp95vgQ5Gh0KhKZjMWmgWFYIhabDoWCkchkPD4Ti01HIpPR6BRwRaNTKDoG4qPRqYmJi/H4DAgjyTRBzIGYAcdcKIpIUt2yDh3n+IcfvldVRdOaq6s3IcjH81vfffefg4ctxzl+8dW/er0vnz/vieLHXu8oSaa//fbf3e4Tjlt7+fLHdtvi+S3D0CWp/kBrMkx+wFpA003DaElSvXl/LxabdrvPQZAPQQKCUDMM3bJMWd6pVjcBGPH4jNc7mpqb1bTmX/7KC0JNVRUcT3o8Ix7PiNc7Clr9sxYViwVBqFWrmzS95PWOgg6GQkGOW+P5LUmqx+MzLpcLnAcuCPK5+j+vd9TlcoG+n0YChv1DHWBYAtC/T/mFXI4GLCaIFEGkSDKN48lsdiGbXQiFguApkcgk2InHZ2h6EceTfQBSC/Pv0vQSw+RxPDlkkShut9tHtv1IlncqlQ1R3J6YuIiiY7Lc+MenD3s9R9f3TfPAtjvgWZHIJEVlHOdYUeQCc62lP5DlHcs6NM0D0zQEoaYocqm0AjpxUgHD5DmOFYQaaMUAA4bJVyoblcpGubxeLq9z3Fq5vC7LjRs3rmNYgue3UnM4w+RLpRUQ8+eP/kRRGdDMAQwnCbLZBZpeoqirLFsql9dzuWUMS6DoWDY7XywWstn51dWbYB7kcsssW6KozMTExWKxcP16DsMSoD+53HKptFIur5dKK4DKQwwkqW6aRrt9ZJoHvd6zzzufvRX/DQT5ZLlhWaZpHjjO03b7qN0+sixTEO4Avtt2x7Y7lcqGLO8Yhq5pTY5jOW6NYa5NTFwcaM312usBkJxlS6urN1m2dLtyC8jkveWlYrHQ7wzHsiWOW8PxJOAMjr8NuAf6tvHBH2l68Re/OuGV230OUGhYAUmmOY7N5ZZpejGXo4H6Q6Fgn1HLN25cp+nFYrFAEHPl8rog3EHRsVhsmmVLGJbAsASgHwCjWCxUKhskmYYg36sEMOyXpPrLlz/adqfXe9brOYJQAwUqiuw4Tw8etrrdJ99883W7fdT94nGxWIAgH0GkbLvzQGsWmGufdz7r9RzHedrtPul2n7x48VyWd8CsfjUqKOoq0AGAkaaXQPLBTZDLLTNMnmHyqblZwBCCSDnOsa7vNxqibXd+/7v3gCyACCgqEw6PD2nq8Yy43efc7l+63eeAPoFcwb7H4x7sQ5AvHB4Hw46iMiSZZpg8SaY9nhHAzn78ycz4GQYMk69WN0Vx+8MPP1AUWdf3KSoDw/7blVuiuA0G0b2725/IUjwe83hGECRAEClJqlNUhqKuNhoiz28piszzHwG5FIuFcHh8qIPblVuWdfjPx48kqY7jSYrK9G+0gCh+rGlNTWuapqFpqmkeSFK9XF6HYX/6t1d0XROEmmkeWNahbXd0fV9R5L8rf2ve3zMMHcMSQGuvZhGolyBS/Vtl9NQ0bRlG697d7Vhserafm6IyEOQjyTSYDSs3ixiWuHL5HcCo2dm3wU0ejU4NMTgzAoEIUHQMIMZxLKDdIAxBApcuvcmypVxuGUzfvp0/PVAHHzInCU5/aJw2UA2gzRkXggRAof/v7ADknwCwiRrKU200wgAAAABJRU5ErkJggg==" nextheight="695" nextwidth="901" class="image-node embed"><figcaption htmlattributes="[object Object]" class="hide-figcaption"></figcaption></figure><p>An audit firm reviews what you put in front of them. They don't monitor your deployments, they don't review your key management, they don't check whether your DevOps practices are secure, and they don't come back six months later to see what you've changed since the audit. When Prisma deployed MigrateTroveZap after the main audit, no auditor raised an alarm. When Resolv designed a system where one EOA could mint unlimited tokens, the auditor saw code that "worked as specified." When Zunami's development went dormant while user funds sat in strategies guarded by a single key, nobody was watching</p><h3 id="h-what-actually-needs-to-happen" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0"><strong>What Actually Needs to Happen</strong></h3><p>The lesson from these three incidents is not "get better audits." The lesson is that audits are one component of a security program, and without the other components, they give you a false sense of security that may be worse than no audit at all.</p><p>Here's what a real security program looks like for a DeFi protocol.</p><p><strong>1. Hire a security person. Full-time. In-house.</strong></p><p>Not a developer who "also does security." Not an auditor on retainer. Someone whose entire job is to think about how your protocol can be attacked. This person maintains the threat model, reviews every deployment, defines access control policies, monitors production, and owns the gap between what was audited and what is running.</p><p>The cost of this person is $200-400K/year. The cost of not having them is measured in the tens of millions — and that's just the direct financial loss, not counting the TVL collapse, the reputational destruction, and the potential legal exposure. Prisma's TVL dropped 60%. Zunami's protocol is effectively dead. Resolv's USR may never recover its peg.</p><p><strong>2. Conduct security architecture reviews, not just code audits.</strong></p><p>Before any code is written, someone should be mapping trust boundaries. Which components have privileged access? What's the blast radius if each one is compromised? Are there on-chain guardrails to limit damage even if off-chain components fail?</p><p>For Resolv, this review would have immediately flagged: "A single EOA with unlimited minting power and no on-chain rate limit is a single point of failure that makes the entire protocol's security dependent on one private key." That's not a subtle finding. Any competent security architect would catch it in a design review.</p><p>For Zunami, the review would have flagged: "The deployer wallet retains god-mode access to strategy contracts including the ability to withdraw all user collateral via withdrawStuckToken(). This must be migrated to a timelocked multisig or revoked."</p><p>For Prisma, the review would have flagged: "MigrateTroveZap has delegation approval over user troves and accepts arbitrary flashloan callbacks without input validation. This needs its own security review before deployment."</p><p><strong>3. Gate every deployment with a security review.</strong></p><p>No contract goes to mainnet without someone asking: What can this contract do? What trust assumptions does it make? What happens if those assumptions are violated? What's the worst case? Is this in the existing audit scope, and if not, does it need its own review?</p><p>This doesn't mean a full external audit for every helper function. It means an internal review by someone who understands the security implications. A 30-minute review of MigrateTroveZap by a security-aware engineer would have caught the input validation issue. A 15-minute review of the SERVICE_ROLE architecture would have flagged the missing mint caps. These are not exotic findings. They're basic security hygiene.</p><p><strong>4. Implement on-chain guardrails as defense in depth.</strong></p><p>Even if you trust your keys, assume they can be compromised and design accordingly. Add rate limits on privileged operations. Add maximum amounts per transaction and per time window. Add timelocks for large operations. Add oracle checks where applicable. Use multisigs instead of EOAs for any privileged role.</p><p>Resolv with a "max 1M USR per mint" cap would have turned a catastrophic exploit into a minor incident. Zunami with a timelock on withdrawStuckToken() would have given the community time to react. Prisma with input validation on the flashloan callback would have prevented the exploit entirely. These are cheap, simple, well-understood engineering practices. The fact that none of these protocols implemented them tells you that nobody with security expertise was reviewing the architecture.</p><p><strong>5. Monitor production continuously.</strong></p><p>Set up alerting for all privileged operations. Large mints, unexpected admin calls, unusual fund movements. The DeFi community learned about the Resolv exploit from Twitter before the protocol team knew. Zunami's community discovered the hack before the team responded (and the first team response on Discord was "rekt lmfao"). This is not acceptable for systems managing hundreds of millions of dollars.</p><p>Real-time monitoring with basic anomaly detection — "a mint just happened that's 500x the deposit amount" or "the deployer wallet just called withdrawStuckToken() for the first time ever" — would have provided early warning and potentially allowed pausing before the damage was done.</p><p><strong>6. Treat security as a continuous process, not an event.</strong></p><p>The traditional model is: build, audit, deploy, done. The reality is: build, audit, deploy, add feature, deploy helper contract, change access control, rotate keys, add new strategy, integrate with new protocol, and on and on. Every post-audit change is a potential attack surface expansion. If nobody is tracking the delta between "what was audited" and "what is live," you're flying blind.</p><p>Maintain a deployment registry. Track audit coverage. Conduct periodic architecture reviews — quarterly at minimum, or whenever the system changes significantly. Re-assess threat models when new components are added. This is not optional overhead. This is basic security operations.</p><h3 id="h-the-organizational-problem" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0"><strong>The Organizational Problem</strong></h3><p>Most DeFi teams are structured as: developers, a product person, maybe a community manager. Security is something that happens once, before launch, when an external firm reviews the code. After that, it's nobody's job.</p><p>This is like a bank outsourcing its risk management to an external consultant who visits once a year. Between visits, the bank adds new products, changes its trading systems, gives master keys to individual employees stored on unencrypted laptops, and deploys new customer-facing tools without review. Then when something goes wrong, the bank points to the consultant's report and says: "But we were audited!"</p><p>Zunami is the most extreme example. Four exploits across three years. Each time, the team promised better security. The V2 launch was explicitly marketed around security, with multiple audits from reputable firms. And then the protocol got drained by a single admin function call because the deployer wallet retained god-mode access and nobody thought to revoke it — or monitor it, or put it behind a multisig, or add a timelock, or do any of the basic things that a security person on staff would have demanded.</p><p>Michael Egorov's comment — "What is worse, admin key existed!" — should be tattooed on the inside of every DeFi founder's eyelids. The admin key existed because nobody whose job was security was in the room when the architecture was designed. The MigrateTroveZap went unreviewed because nobody whose job was security was tracking post-audit deployments. The SERVICE_ROLE was a single EOA because nobody whose job was security was asking "what if this key leaks?"</p><h3 id="h-the-bottom-line" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0"><strong>The Bottom Line</strong></h3><p>Three protocols. Three stablecoins. Three exploits. All in the Curve ecosystem. All audited. All hacked through the same fundamental gap: the space between what the auditor reviewed and what actually determines the protocol's security.</p><p>Code audits catch code bugs. They don't catch architectural flaws, operational security failures, peripheral deployment gaps, or the absence of on-chain guardrails. The DeFi industry has spent millions on audits while spending almost nothing on the security engineering, threat modeling, and continuous monitoring that actually prevents exploits.</p><p>If you're running a protocol with real TVL and you don't have a security engineer on staff — someone who reviews every deployment, maintains the threat model, defines access control policy, monitors production, and asks "what if?" every single day — then your next audit report is just a very expensive piece of paper that will look great in your post-mortem.</p><p>Hire the person. Build the process. Treat security like what it is: not a checkbox before launch, but an ongoing engineering discipline that requires dedicated people, continuous attention, and the organizational authority to say "no, we don't deploy this until the security questions are answered."</p><p>The alternative is being the next entry in the table above.</p><hr><p><em>This article compares three exploits in the Curve ecosystem: Prisma Finance ($12M, March 2024 — unaudited MigrateTroveZap contract), Zunami Protocol ($500K, May 2025 — admin key draining via withdrawStuckToken()), and Resolv Labs ($25M+, March 2026 — single-key signer with unlimited minting power). All three passed code audits. All three were exploited through non-code security failures.</em></p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
            <category>defi</category>
            <category>web3</category>
            <category>security</category>
            <category>contracts</category>
            <category>crypto</category>
            <category>architecture</category>
            <category>audit</category>
            <category>blockchain</category>
            <enclosure url="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/a0803ddc8864c19c2db69fef8fed39387c3239a6abf1187f015719261074a6c9.jpg" length="0" type="image/jpg"/>
        </item>
        <item>
            <title><![CDATA[Главная уязвимость DeFi: оракулы или Затемнённая Цепь.]]></title>
            <link>https://paragraph.com/@defi-in-security/defi-2</link>
            <guid>swipCokoprcLbAzxC3a1</guid>
            <pubDate>Sun, 01 Jun 2025 21:11:23 GMT</pubDate>
            <description><![CDATA[ВведениеДецентрализованные финансовые приложения (DeFi) полагаются на оракулы – механизмы, доставляющие внешние данные (например, цены активов) в блокчейн-смартконтракты. Без надежных оракулов невозможна работа таких ключевых функций, как выдача займов под залог, расчет депозитов/выплат по деривативам и т.д. При этом сами оракулы давно называют «ахиллесовой пятой» DeFi, ведь уязвимость в цепочке доставки данных способна свести на нет всю гарантируемую смарт-контрактами децентрализацию. Как от...]]></description>
            <content:encoded><![CDATA[<h2 id="h-vvedenie" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Введение</h2><p>Децентрализованные финансовые приложения (DeFi) полагаются на <strong>оракулы</strong> – механизмы, доставляющие внешние данные (например, цены активов) в блокчейн-смартконтракты. Без надежных оракулов невозможна работа таких ключевых функций, как выдача займов под залог, расчет депозитов/выплат по деривативам и т.д. При этом сами оракулы давно называют «ахиллесовой пятой» DeFi, ведь уязвимость в цепочке доставки данных способна свести на нет всю гарантируемую смарт-контрактами децентрализацию. Как отмечают эксперты, протоколы <em>безоговорочно</em> доверяют входящим данным: любое значение, предоставленное оракулом, сразу используется для расчётов, что превращает оракул в критическую точку отказа.</p><p>Даже <strong>пионеры DeFi</strong> рано осознали эту проблему. Так, Андре Кронье (создатель Yearn Finance) указывал, что устойчивость DeFi-систем подтачивают проблемы с ценовыми данными и манипуляцией рынков. В 2025 году основатель фирмы Chaos Labs прямо назвал оракулы «одним из самых слабых звеньев DeFi». Чтобы понять масштаб: только за 2022 год атаки, связанные с манипуляцией оракульными ценами, привели к потерям в ~$403 млн на 41 инцидент. Иначе говоря, уязвимость лежит не в коде блокчейна, а «на стыке» с внешним миром, где злоумышленники научились эксплуатировать доверие протоколов к поступающим данным.</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/4e38aea14430561ff0994dbcead684a7294989517bc80d65b830c9da23a48d26.png" alt=" Рис. 1: Оракулы служат “мостом” между блокчейнами и внешними данными, поставляя цены и другие сведения в смарт-контракты." blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">Рис. 1: Оракулы служат “мостом” между блокчейнами и внешними данными, поставляя цены и другие сведения в смарт-контракты.</figcaption></figure><p>Сегодня наиболее распространены ценовые оракулы для курсов токенов. Они берут котировки с бирж и других источников, агрегируют их и публикуют ончейн. Ниже мы подробно рассмотрим архитектуру ведущего оракульного решения <strong>Chainlink</strong>, разберём типовые уязвимости и проанализируем резонансные инциденты (Fantom/Scream, deUSD/Euler, Mango Markets, bZx и др.). Мы также оценим технические причины атак, их последствия для экосистем, и обсудим современные методы защиты (децентрализация оракулов, модели на основе AMM-кривых, самописные решения, дублирование источников) с рекомендациями для DAO, разработчиков и аудиторов.</p><h2 id="h-arhitektura-chainlink-i-uyazvimye-patterny" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Архитектура Chainlink и уязвимые паттерны</h2><p><strong>Chainlink</strong> – крупнейшая децентрализованная оракульная сеть, обеспечивающая ценовыми данными множество DeFi-протоколов. По оценкам, Chainlink сейчас защищает смарт-контракты на сумму ~$45 млрд более чем в 20 разных блокчейнах. Архитектура Chainlink предполагает набор независимых узлов-валидаторов, которые запрашивают цену актива с внешних рынков, а затем отправляют полученные значения в on-chain агрегатор. Агрегатор, в свою очередь, вычисляет <strong>итоговый ценовой ориентир</strong> – как правило, используя медиану или средневзвешенную цену по объёму (VWAP) из присланных узлами данных. Такой подход призван отфильтровать шум и единичные выбросы: например, если на одной бирже произошёл случайный всплеск цены, медианное значение по десяткам источников сгладит этот эффект. В случае Chainlink для ряда стейблкоинов и менее ликвидных активов используется именно <em>объемно-взвешенная средняя цена (VWAP)</em> по всем доступным рынкам, что повышает устойчивость к манипуляциям краткосрочными сделками.</p><p><strong>Преимущества модели Chainlink:</strong> Благодаря множеству независимых узлов и источников данных, устраняется единая точка отказа, а риск ошибки снижается за счёт консенсуса узлов. Децентрализованный сбор данных повышает надёжность: данные агрегируются и проверяются несколькими независимыми участниками, что значительно лучше прямого доверия одной бирже или API. Chainlink внедрил протокол Off-Chain Reporting (OCR), где узлы сначала обмениваются данными между собой off-chain, приходят к консенсусу об цене, и лишь после этого отправляют одно сжатое обновление on-chain – это снижает расходы газа и позволяет увеличить число источников без перегрузки блокчейна. Кроме того, заложены механизмы контроля: например, ценовые фиды обновляются только при изменении цены более чем на заданный порог (деятельность <em>деviation threshold</em>), чтобы избежать излишней волатильности или манипуляций. В совокупности эти меры сделали Chainlink отраслевым стандартом: многие DAO доверяют ему безопасность ликвидности на миллиарды долларов.</p><p><strong>Уязвимые места и ограничения:</strong> Полностью устранить риски не удалось. Во-первых, если базовый рынок актива малоликвиден или подвержен <strong>координированной манипуляции</strong>, даже децентрализованный оракул будет транслировать “плохие” данные – ведь он честно отражает внешние торги. VWAP-агрегатор устойчив к кратким всплескам, но уязвим, если злоумышленник создаст большой объём фиктивных торгов. Пример – случай со стейблкоином <strong>deUSD</strong> на платформе Euler: на одном из пулов Curve единичная крупная сделка заняла ~50% суточного объёма торгов, временно подняв цену deUSD выше $1; оракул Chainlink точно зафиксировал эту аномалию в расчёте VWAP, что и привело к проблемам (см. подробности ниже). Во-вторых, сама сеть узлов требует доверия к добросовестности большинства. Хотя случаи злонамеренного сговора валидаторов Chainlink неизвестны, теоретически <strong>атака 51%</strong> или массовый сбой узлов могут нарушить работу фида. Chainlink планирует решить это внедрением ставки токена LINK и слэшинга (штрафов) для узлов за неверные данные, но на момент обзора эта система только развивается. В-третьих, обновления цены происходят не постоянно, а с определённой частотой или при превышении порога отклонения. В периоды экстремальной волатильности возможны задержки обновлений, и если рынок движется быстрее оракула, у атакующих появляется окно возможностей (например, взять кредит по старой цене до обновления фида).</p><p>Наконец, стоит отметить, что Chainlink не охватывает все активы и все сети – на новых или нишевых блокчейнах проекты иногда вынуждены прибегать к <strong>самописным оракулам</strong> или упрощённым решениям. Классический пример – протокол Scream на Fantom, который до интеграции с Chainlink использовал фиксированные цены для ряда активов, что обернулось катастрофой (см. ниже). Таким образом, даже лучшая на сегодня модель оракулов имеет слабые места: от человеческого фактора (неправильная интеграция или настройка фида) до фундаментальной зависимости от внешних рынков. Chainlink значительно укрепил защиту (по сравнению с единичными централизованными оракулами или прямым использованием цен DEX), <strong>но полностью устранить уязвимости ценовых данных невозможно</strong> – остаётся “трилемма” между безопасностью, децентрализацией и доступностью данных.</p><h2 id="h-obzor-incidentov" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Обзор инцидентов</h2><p>За последние годы произошло множество атак и сбоев, связанных с оракулами. Рассмотрим несколько знаковых инцидентов – как с использованием Chainlink, так и альтернативных механизмов – чтобы понять, какие паттерны эксплуатировались атакующими.</p><ul><li><p><strong>Fantom / Scream (стабильные монеты и stETH)</strong> – Весной 2022 г. на блокчейне Fantom популярный лендинговый протокол Scream столкнулся с крупными долгами из-за <em>некорректной цены оракула</em>. В погоне за “надежностью” разработчики Scream <strong>жёстко зафиксировали цену</strong> некоторых залоговых токенов (в том числе алгоритмического стейблкоина fUSD от Fantom и stablecoin DEI от Deus Finance) ровно на уровне $1. Когда эти «стабильные» токены в реальности потеряли привязку и подешевели на рынке, платформа этого не отразила – для смарт-контракта они по-прежнему стоили $1. Пользователи немедленно воспользовались ситуацией: массово вносили обесценившиеся fUSD/DEI в качестве залога по завышенной цене и выводили взаймы нормальные стабильные монеты (USDC, USDT) и другие активы из протокола. В итоге Scream остался с <em>«мёртвым» долгом</em> примерно на $35 млн – резервов не хватило покрыть обязательства. Кроме того, на Fantom у Scream, вероятно, была неправильно настроена цена для стейкингового дериватива stETH (Lido Staked Ether): судя по отчетам, его котировка также не обновлялась своевременно. Инцидент подорвал доверие: TVL (общая заблокированная стоимость) Scream рухнула с более $1 млрд до ~$38 млн, а команда в экстренном порядке объявила о скорейшей интеграции Chainlink-оракулов для всех активов. Кейс Scream иллюстрирует <em>ошибку конфигурации оракула</em>, фактически <strong>отсутствие надёжного источника цены</strong>, что привело к прямой возможности арбитража против протокола.</p></li><li><p><strong>deUSD на Euler (инцидент 2025 г., спор Bentley vs. Zeller)</strong> – Свежий пример того, как даже децентрализованные оракулы могут вызвать спорные ситуации. В мае 2025 г. на платформе Euler (сеть Avalanche) один из пользователей потерял свыше $500 тысяч из-за принудительной ликвидации, вызванной скачком цены стейблкоина <strong>deUSD</strong>. Оракул Chainlink для deUSD неожиданно показал цену $1.03 (вместо нормального $1), что трактовалось протоколом как падение обеспечения – позиции, занимавшие deUSD, были ликвидированы. Первоначально это назвали <em>«сбоем Chainlink»</em>, однако вскоре выяснилось, что оракул сработал согласно правилам: на децентрализованной бирже Curve прошла крупная сделка, отвязавшая deUSD от доллара (курс временно подскочил выше паритета), и Chainlink <strong>корректно зафиксировал этот рыночный факт</strong> в агрегированном VWAP-фиде. Возникла дискуссия между Майклом Бентли (сооснователем Euler) и Марком Зеллером (представителем Aave Chan Initiative) относительно виновника ситуации. Бентли намекал, что оракул сработал “ненадёжно”, тогда как Зеллер возразил: <em>протоколы не должны обращаться с волатильными или неликвидными активами так, будто они полностью надёжны</em> – риск лежит на платформе, выбравшей такой залог. По словам Зеллера, <strong>Chainlink “выполнил свою работу”</strong>, предоставив данные в точном соответствии с рыночной динамикой, а ответственность за потери несёт неправильная оценка рисков со стороны проекта. Данный инцидент высветил конфликт между провайдером оракулов и разработчиками DeFi: где грань между “некачественными данными” и “ошибкой протокола в работе с данными”? В итоге сообщество сошлось во мнении, что deUSD был слишком слабо ликвиден, и <strong>Euler стоило ввести ограничения</strong> (например, не разрешать брать большой кредит под обеспечение из такого токена, или внедрить лимиты отклонения цены). Случай deUSD/Euler показал, что даже без явного хакера можно получить ущерб, если реальный рынок актива нестабилен – оракул лишь отражает эту нестабильность, а протокол должен уметь ее смягчать.</p></li><li><p><strong>Mango Markets (Solana, октябрь 2022)</strong> – Один из самых громких примеров <em>классической манипуляции ценой через оракул</em>. Платформа Mango являлась DeFi-биржей/лендингом на Solana и допустила использование собственного токена управления MNGO в качестве залога. Атакующий (Авраам Айзенберг) заметил, что рынок MNGO слаболиквиден и поддаётся разовому разогреву. Он накопил капитал (~$10 млн USDC) и провёл серию согласованных торгов: с одного аккаунта начал агрессивно покупать MNGO, а с другого продавать, разгоняя цену токена <strong>в десятки раз за минуты</strong>. Внешние ценовые оракулы (на Solana использовались Pyth и внутренние данные Mango) зафиксировали огромный рост стоимости MNGO. В результате злоумышленник «на бумаге» увеличил стоимость своего залогового аккаунта с $10 млн до ~$400 млн, после чего под этот фальшиво завышенный залог <strong>вывел из Mango практически всю ликвидность</strong> в стабильных монетах и других токенах. Когда цена MNGO вернулась к нормальным значениям, платформа осталась с невозмещенными долгами на сумму более $100 млн. Примечательно, что Айзенберг затем публично заявил, будто его действия были <em>«легитимной торговой стратегией»</em>, а не взломом – мол, код протокола работал как написано, а он просто воспользовался выгодной возможностью. Однако сообщество и регуляторы не согласны: против него были выдвинуты обвинения в рыночной манипуляции (SEC, CFTC и Минюст США квалифицируют это как мошенничество, несмотря на отсутствие “взлома кода”). Mango DAO, чтобы спасти остатки средств, вынужден был пойти на сделку: проголосовал за то, чтобы атакующий вернул примерно половину выведенных активов, оставив себе остальное в качестве “баунти”, и освобождался от юридической ответственности. Этот инцидент стал хрестоматийным примером <em>атаки на оракул через раздувание собственной стоимости</em>: использование собственного governance-токена в качестве залога без надёжного ценового ограничения оказалось фатальной ошибкой дизайна.</p></li></ul><p><em>Пример динамики цены при атаке на оракул: график пары MNGO/USDC во время эксплойта Mango Markets (октябрь 2022). Видно резкий всплеск курса MNGO почти до $1 (+1182% за считанные минуты), с последующим обвалом ниже исходных значений. Оракул зафиксировал “пиковую” цену, позволив злоумышленнику взять кредиты под переоцененный залог и обналичить их, пока цена не вернулась к норме.</em></p><ul><li><p><strong>bZx (Ethereum, 2020)</strong> – Первое известное <strong>flash loan</strong>-ограбление через уязвимость оракула. В феврале 2020 платформу bZx (протокол маржинальной торговли Fulcrum) атаковали, воспользовавшись тем, что для расчёта цен залогов она брала данные напрямую с децентрализованной биржи Uniswap. Атакующий одолжил большое количество ETH с помощью мгновенного кредита (flash loan) и за один блок совершил несколько операций: <strong>разогнал цену</strong> малоликвидного токена (WBTC) на Uniswap, после чего немедленно открыл на bZx позицию, используя этот токен по завышенной цене, и вывел с платформы ценные активы, вернув флэш-кредит. Все произошло за секунды, пока цена WBTC на Uniswap была искусственно высока – протокол не успел среагировать. Убыток тогда составил относительно скромные ~$350 тыс., но инцидент прозвучал тревожным звонком для всей отрасли. В последующие два года подобные атаки через мгновенные кредиты и манипуляции ценами множились, нанеся суммарно ущерб в <strong>сотни миллионов долларов</strong> по различным протоколам. Помимо bZx, пострадали проекты <strong>Value DeFi, Harvest Finance, Inverse Finance, Cream, Saddle</strong> и другие – схемы зачастую схожи (разгон цены низколиквидного токена + взятие кредита под него + вывод ликвидности, оставляя “пустышку” в залоге). Многие из этих атак были возможны из-за отсутствия интеграции с Chainlink или другим надёжным агрегатором – проекты либо полагались на единственный DEX для цен (как bZx), либо не имели ограничений на величину ценовых скачков.</p></li></ul><p>Конечно, перечисленными случаями проблема не исчерпывается. Были и курьёзные эпизоды: например, в 2019 г. протокол Synthetix из-за ошибки оракула получил неверный курс корейской воны, что позволило боту «напечатать» синтетических активов на фантастическую сумму (ошибку оперативно откатили). Однако вышеописанные события – Fantom/Scream, Euler, Mango, bZx – дают репрезентативную выборку сценариев, на которых стоит сосредоточиться при анализе.</p><h2 id="h-tehnicheskij-analiz-prichin-atak" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Технический анализ причин атак</h2><p>Рассмотрим, <strong>как именно реализуются атаки на оракулы</strong>, и где проходит грань между багом, недосмотром и системной уязвимостью. Общий признак всех подобных инцидентов: злоумышленник (или стечение обстоятельств) предоставляют протоколу <strong>ложные ценовые сигналы</strong>, на основе которых смарт-контракты совершают экономически невыгодные действия (ликвидируют “здоровые” позиции, выпускают лишние средства под недействительный залог, позволяют вывести больше активов, чем положено и т.д.).</p><p>С точки зрения реализации можно выделить несколько типовых паттернов:</p><ul><li><p><strong>Манипуляция ценой на источнике данных (DEX/oracle feed)</strong>. В классическом случае атакующий использует крупный капитал (свой или привлечённый через flash loan), чтобы изменить цену актива на рынке, откуда оракул берёт данные. Если оракул привязан к одной DEX, злоумышленник может прокрутить через эту DEX большой объём торгов за короткое время, создав видимость скачка цены. Даже если оракул агрегирует несколько источников, недостаточная ликвидность позволяет совершить такие операции сразу на всех основных площадках (или на наиболее весомых в агрегате), чтобы повлиять на среднюю цену. Именно так действовал атакующий Mango: путем <strong>быстрого увеличения торгового объема</strong> и цены MNGO на внутренней бирже протокола он добился многократного роста “рыночной” цены. В случае bZx 2020 г. и многих последующих атак на кредитные протоколы схема схожа – атакующий разгоняет курс залогового токена, используя тонкий рынок, после чего берет под этот токен крупный заем и обрушивает цену обратно. Важно отметить: для таких операций идеально подходят flash loans – мгновенные беззалоговые кредиты, которые позволяют получить миллионы на одну транзакцию. Благодаря им атакующие в 2020–2021 гг. совершали молниеносные атаки без собственного начального капитала.</p></li><li><p><strong>Некачественные или неподходящие источники оракула</strong>. Иногда проблема кроется не в злонамеренных действиях, а в <em>дизайне протокола</em>. Пример – история Scream, где разработчики фактически отключили обновление цен (зафиксировали курс стабкоинов на $1). Формально никто “не атаковал” Scream – пользователи просто воспользовались ошибочным допущением системы. Это ближе к <strong>недосмотру архитектуры</strong>: оракул считался тривиальной частью, ему не уделили должного внимания, в результате чего протокол не отражал реальность. Схожим образом, если проект вручную поддерживает ценовой фид (через админа или скрипт) и вовремя не обновит его – могут возникнуть возможности для эксплуатации. Тут граница между багом и уязвимостью размыта: с одной стороны, никакого сбоя кода нет – контракт делает, что ему сказали (как в Mango: контракт честно принял завышенную цену как есть). С другой – упущение разработчиков (непредусмотренность проверки цен на аномалии, выбор неподходящего источника) можно считать <strong>логической уязвимостью</strong>.</p></li><li><p><strong>Отсутствие ограничений и sanity-check при использовании данных</strong>. Многие успешные эксплойты стали возможны, потому что протоколы принимали любую цену от оракула <em>на веру</em>, без дополнительных проверок. Например, если бы в Mango или Scream были встроены элементарные правила типа: “если цена актива X выросла &gt; 2х за час – приостановить заимствования/ликвидации”, атака могла быть смягчена. Такой функционал называют <em>circuit breaker</em> или <strong>санити-чек</strong>. В анализе от CertiK подчеркивается: для защиты от манипуляций протоколы должны внедрять многослойные меры – мульти-источниковые оракулы, аудит всей цепочки данных, fallback-логика при аномальных отклонениях, мониторинг и аварийное отключение при подозрительной волатильности. Если этого нет, даже небольшая брешь в оракуле превращается в полный компромисс протокола. В примере deUSD/Euler мы видим, что <strong>границы допустимого отклонения не были настроены</strong> – оракул сообщил +3 цента к цене стейблкоина, и смарт-контракты тут же провели ликвидации, хотя более разумно было бы игнорировать такие отклонения для малоликвидного актива. Таким образом, отсутствие внутренних проверок – это <em>недоработка проекта</em>, усугубляющая уязвимость оракула.</p></li><li><p><strong>Системные уязвимости и рыночные аномалии</strong>. Наконец, часть ситуаций лежит за пределами классического понимания “бага”. Например, общесетевые сбои или экстремальные события – внезапный обвал рынка, отключение бирж, форки – могут приводить к сбоям оракулов. В истории DeFi были случаи, когда из-за перегрузки сети оракул не успевал обновить цену, и это позволяло должникам вывести залоги, пока протокол видел устаревшую высокую цену. Иногда сами биржи отдавали некорректные данные (случай Synthetix с неверной ценой sKRW из-за ошибки API). Эти эпизоды показывают <strong>системный характер рисков</strong>: даже без злоумышленника, техническая сложность инфраструктуры оракулов может приводить к инцидентам. Поэтому грань между “взломом” и “форс-мажором” бывает размыта – любая уязвимость в экосистеме (будь то баг оракула, сбой сети или человеческая ошибка) бьет по DeFi-протоколу напрямую.</p></li></ul><p>Важно подчеркнуть: в большинстве атак на оракулы <strong>код смарт-контрактов не нарушается</strong> – злоумышленники эксплуатируют экономическую логику. Это отличает такие инциденты от типичных багов (переполнений, reentrancy и т.д.). Протокол “теряет деньги” не потому, что кто-то взломал приватный ключ или получил прямой доступ к средствам, а потому, что <em>он сам добровольно отдал средства</em>, полагаясь на неправильные входные данные. В этом смысле oracle-exploit – это <em>финансовая атака</em>, зачастую требующая глубокого понимания рынка. Например, атака Mango была столь же операцией на бирже, сколь и хакерством. Айзенберг (Mango) и другие атакующие даже утверждали, что не делают ничего незаконного. Однако регуляторы все чаще трактуют такие манипуляции как <strong>мошенничество</strong> и преследуют их наряду с традиционными взломами. Это подтверждает, что суть проблемы – в подрыве доверия к системе: если можно исказить цены, DeFi не может считаться надежной финансовой инфраструктурой.</p><h2 id="h-posledstviya-dlya-ekosistem" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Последствия для экосистем</h2><p>Атаки и сбои ценовых оракулов наносят ущерб не только отдельным жертвам, но и экосистеме в целом. Рассмотрим последствия описанных выше инцидентов:</p><ul><li><p><strong>Прямые финансовые потери и пострадавшие стороны.</strong> В каждом случае находилась сторона, понесшая материальный урон. В Scream это были, по сути, вкладчики протокола – их ликвидность ушла в руки эксплуататоров, оставив “дыру” в балансе платформы ~$35 млн. В итоге Scream оказался подкапитализирован: пользователи с fUSD/DEI не могли вывести свои депозиты, а другие кредиторы получили лишь частичные выплаты. В случае Mango пострадали держатели депозитов и контрагенты по сделкам – протокол потерял ~$100+ млн ликвидности, многие пользователи оказались с обесцененными токенами MNGO. Атакующий вернул около половины, но вторую оставил себе как “награду”, то есть прямой ущерб для DAO и пользователей составил десятки миллионов. В истории Euler/deUSD непосредственным пострадавшим стал конкретный трейдер, чей залог принудительно ликвидировали на полмиллиона долларов – неприятность локальная, но для этого пользователя деньги утраченны безвозвратно. В bZx 2020 команда покрыла убыток ~$350k из резервов, то есть ущерб лег на инвесторов/разработчиков. Подобные паттерны повторялись и в других случаях: например, в <strong>Inverse Finance</strong> (июнь 2022) атака на оракул стоила протоколу ~$1.2 млн, а в <strong>Harvest Finance</strong> (2020) – около $34 млн, причём во втором случае часть средств попытались вернуть добровольно, но большинство пользователей понесли потери.</p></li><li><p><strong>Реакция проектов и сообществ (DAO).</strong> Столкнувшись с последствиями, DeFi-сообщества реагировали по-разному. Некоторые протоколы были вынуждены признать поражение и свернуть деятельность (особенно в ранние годы, когда не было фондов для компенсаций) – к счастью, Scream и Mango избежали полного закрытия. Часто прибегают к <strong>экстренным голосованиям DAO</strong>: так, Mango провёл голосование, утвердившее “сделку” с хакером о частичном возврате средств и покрытии остального ущерба из казны DAO. В случае Scream команда обратилась за помощью к Fantom Foundation; та, по сообщениям, выделила средства на запуск бота-ликвидатора, чтобы как можно быстрее погасить часть задолженностей и восстановить платежеспособность протокола. Euler Finance после инцидента deUSD объявила, что проведет анализ и, вероятно, ужесточит критерии листинга стейблкоинов с низкой ликвидностью, хотя о компенсации речи не шло (т.к. протокол формально работал правильно). Позитивный пример – <strong>большой взлом Euler в марте 2023</strong> (не связанный с оракулом, но показательный): команда в итоге договорилась с хакером о возврате ~90% украденных $200 млн и полностью компенсировала пользователей. Это свидетельствует о взрослении отрасли: проекты стремятся не бросать пользователей с убытками. Тем не менее, в большинстве случаев oracle-атаки рассматриваются как <em>рисковая деятельность пользователя</em>: если ты берешь кредит под экзотический залог, будь готов потерять деньги. Поэтому компенсации – скорее исключение (Mango – уникальный случай, где DAO имел средства и рычаги договориться с хакером).</p></li><li><p><strong>Влияние на TVL, токены и доверие.</strong> Инциденты с оракулами часто подрывают репутацию протоколов и ведут к оттоку ликвидности. Мы уже упоминали обвал TVL Scream с $1.1 млрд до ~$38 млн (-96%) – фактически, протокол перестал быть значимым игроком на Fantom после той ошибки. Токен управления Scream (SCREAM) тоже просел в цене, а новые запуски на Fantom стали с недоверием относиться к рискам. Mango Markets после октябрьского взлома так и не вернул прежний объем торгов – доверие было подорвано, многие пользователи ушли, а сам случай бросил тень на весь Solana-DeFi, показав уязвимость локальных оракулов. Стоит отметить, что <strong>каждый крупный инцидент усиливает внимание</strong> к проблеме: после случаев bZx в 2020 почти все протоколы отказались от цен с одиночных DEX в пользу агрегаторов (Chainlink и аналоги). После Mango 2022 многие платформы пересмотрели список принимаемых в залог токенов, исключив собственные governance-токены или малоликвидные активы, либо снизив по ним плечи. Инцидент deUSD 2025 вызвал оживлённую дискуссию в Crypto Twitter и на форумах: некоторые обвинили Chainlink в “глюке”, другие защищали его. В итоге для отрасли это стало уроком о <strong>необходимости дополнительного контроля</strong> поверх оракула. В целом, повторяющиеся oracle-эксплойты негативно влияют на восприятие DeFi со стороны институциональных игроков: риск “ложной ликвидации” или манипуляции ценами отпугивает консервативный капитал. С другой стороны, каждый инцидент – это стимул совершенствовать защиту, о чём поговорим далее.</p></li><li><p><strong>Компенсации и страховые механизмы.</strong> В последние годы появились децентрализованные страховые протоколы (Nexus Mutual, InsurAce и др.), предлагающие полисы от сбоев смарт-контрактов. Однако компенсации именно по oracle-атакам – сложный вопрос, т.к. формально код не багнут. Иногда DAO сами создают компенсационные фонды: например, после взлома Compound (не oracle, но показательно) сообщество выпустило токены для возмещения пострадавшим. В случаях с оракулами подобных практик мало – скорее, делают выводы для будущего, чем возмещают прошлое. Таким образом, прямое финансовое возмещение редко покрывает все убытки пользователей, поэтому <strong>репутационные потери</strong> для протокола зачастую даже важнее разового ущерба.</p></li></ul><h2 id="h-tekushie-podhody-k-mitigacii-i-predlozheniya-po-uluchsheniyu" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Текущие подходы к митигации и предложения по улучшению</h2><p>Проблема надёжных оракулов находится в центре внимания сообщества, и за последние годы выработан ряд подходов для снижения рисков. Ниже перечислены как уже применяемые методы, так и перспективные идеи, способные улучшить ситуацию:</p><ul><li><p><strong>Децентрализация и диверсификация оракулов.</strong> Один из принципов – <em>не полагаться на единый источник</em>. Даже использующийся сегодня Chainlink можно подстраховать: некоторые протоколы берут данные сразу из двух оракулов (например, Chainlink + Band, или Chainlink + собственный DEX-TWAP) и сравнивают их. Если расхождение превышает порог – срабатывает аларм, приостанавливаются критические операции. Такое дублирование повышает устойчивость: атакеру пришлось бы одновременно взломать/обмануть оба канала. Также развивается <strong>мультисигнальный подход</strong>: например, Compound v3 использует цены нескольких бирж и Chainlink, а MakerDAO долгое время опирался на собственный коллектив оракулов (группа из 20+ фидеров, передающих данные, с агрегированием медианы). Эксперты рекомендуют агрегировать данные из <em>нескольких независимых источников</em>, чтобы исключить изолированные аномалии. В идеале – сочетать данные CEX и DEX, разные методики (VWAP, TWAP, спот-цена) и разных провайдеров. Чем более разнородные источники, тем сложнее одновременная манипуляция.</p></li><li><p><strong>“Curve-like” модели и встроенные ценовые механизмы.</strong> Инновационный подход – <strong>отказаться от внешних оракулов</strong>, заложив ценообразование внутрь самого протокола. Например, новые алгоритмические стабилизационные протоколы и AMM-пулы реализуют принцип, при котором цена актива вычисляется на основе балансов в пуле ликвидности (формула AMM) и автоматически поддерживается арбитражерами. Проще говоря, протокол сам выступает маркет-мейкером, и <em>его смарт-контракт знает цену из собственного состояния</em>. Классический AMM (Uniswap, Curve) можно рассматривать как on-chain оракул – и действительно, Uniswap v2 предоставлял функцию TWAP (средневзвешенной по времени цены) прямо из контракта, что активно использовалось проектами. <strong>Curve Finance</strong> пошёл дальше: в своём новом лендинговом протоколе crvUSD применяется механизм LLAMMA, который непрерывно ликвидирует и восстанавливает позиции за счёт внутренняя AMM-кривой между залогом и стабильной монетой. Это по сути <em>oracle-less модель</em>: внешняя цена нужна лишь опосредованно (для арбитража), а сам протокол видит цену через коэффициент баланса в пуле. Такие <strong>кривые цены</strong> устойчивее к мгновенным выбросам – чтобы их обмануть, нужно внести огромный капитал и понести существенные потери на проскальзывании. Однако “кривые” оракулы применимы не для всех случаев – в основном для пар со предсказуемой привязкой (стейблкоин-стейблкоин, корзины активов). Тем не менее, проекты экспериментируют: например, некоторые стейблкоины используют Curve-пулы для определения курса при отклонении от паритета. Идея в том, чтобы максимально перенести формирование цены <strong>в on-chain среду</strong>, где ее проще контролировать и где атака требует реальных затрат (арбитраж быстро возвращает цену к честной).</p></li><li><p><strong>Самописные оракулы с узкой специализацией.</strong> В ряде случаев протоколы, недовольные существующими решениями, разрабатывают свои оракулы, настроенные под конкретные задачи. Пример – Keep3r Network от Андре Кронье: в ней реализован оракул, использующий экстремально длительные скользящие средние (например, <em>суточная средняя цена</em> токена). Такая инерционная модель полностью устраняет кратковременные всплески – манипулятору пришлось бы поддерживать фальшивую цену целые сутки, что практически невозможно. Обратная сторона – медлительность реакции; такой оракул годится не для всех финансовых приложений (скорее для неспешных операций вроде ребалансировок). Другой пример – проекты, работающие только со специфическими активами. Они могут агрегировать данные “вручную”: например, протоколы деривативов иногда берут цену из фьючерсной биржи + индексы волатильности, и делают собственный расчет цены актива на смарт-контракте. Если команда обладает экспертизой, собственный оракул даёт гибкость (можно задать любую логику: усреднение, отсечение выбросов, пауза при аномалиях и т.д.). Однако <strong>создание оракула – сложная и опасная затея</strong>: нужен круглосуточный мониторинг, защита от сбоев, экономический анализ. Поэтому большинство всё же предпочитает аутсорсить эту задачу таким сетям, как Chainlink, вместо того чтобы “изобретать колесо”. Оптимальный подход – гибридный: взять проверенный внешний оракул, но обернуть его собственной прослойкой проверок и логики.</p></li><li><p><strong>Дублирование и аварийные лимиты.</strong> Как упоминалось, дублирование источников – мощный прием. Помимо этого, протоколы вводят <em>пределы на изменения цены</em>: например, если цена стейблкоина отклоняется &gt; X% от $1 – приостанавливать определенные операции (ликвидации, минт новых токенов). MakerDAO имеет механизм <strong>Oracles Security Module (OSM)</strong> – задержка поступления нового ценового значения на 1 час, что даёт время заметить что-то неладное и, в крайнем случае, вручную остановить систему прежде, чем “плохая” цена повлияет на казну. Другие протоколы рассматривают введение <em>ценовых диапазонов</em>: например, не доверять оракулу, если он показал цену вне интервала [мин;макс], заданного по историческим данным или экспертно. Конечно, слишком жёсткие ограничения могут помешать сработать честным ликвидациям во время реального краха рынка. Поэтому тут нужен баланс: <strong>circuit breaker</strong> должен использоваться как крайняя мера при явно ненормальных показателях. В целом, тенденция такая: проекты добавляют в смарт-контракты функции “pause” и “guarded launch”, позволяющие при внезапных аномалиях быстро остановить торги/заимствования и созвать команду/DAO для разбирательств.</p></li><li><p><strong>Сети оракулов 2.0 и новые протоколы.</strong> Появляются и совершенно новые решения проблемы оракулов. Например, протокол <strong>Pyth Network</strong> (популярный в Solana экосистеме, а теперь и на Ethereum L2) предлагает высокочастотные ценовые обновления напрямую от бирж и маркет-мейкеров. У Pyth цена публикуется в ончейн-среду не постоянно, а по подписке (consumer pull model) – это позволяет иметь сотни источников, но ставит задачу доверия к самим паблишерам. Тем не менее, Pyth уже используется для второстепенных фидов (на тот же Mango, к слову, фид MNGO шел через Pyth). Другой проект – <strong>API3 (Airnode)</strong> – продвигает идею <em>первичных оракулов</em>: когда сами поставщики данных (биржи, агрегаторы) размещают свои API на блокчейне, минуя посредников. Это снижает количество звеньев, потенциально повышая надёжность (но тут вопрос, насколько сами поставщики децентрализованы – чаще всего нет). MakerDAO в 2023 году выделила свой oracle-подразделение в отдельную компанию Chronicle Labs, которая намерена коммерциализировать наработки Maker (оракулы для DAI) и предоставить их другим протоколам. Их упор – на <strong>верифицируемость</strong>: использование криптографических доказательств правильности данных, чтобы не приходилось слепо доверять узлам. Chainlink не стоит на месте – в roadmap у них <em>Proof-of-Reserve</em> (специальные оракулы для подтверждения резервов стейблкоинов и wrapped-активов), активное развитие межсетевого протокола CCIP (для передачи данных и сообщений между блокчейнами) и упомянутая система staking+slashing, чтобы узлы были экономически мотивированы не халатно относиться к работе. Все это снижает вероятность случайных сбоев и медленных реакций.</p></li></ul><p>Подводя итог, современные подходы к митигации можно свести к простой мысли: <strong>избыточность и проверки</strong>. Никто больше не полагается на единичный показатель. Чем больше независимых подтверждений получает протокол о том, что цена верна, тем безопаснее. Это достигается комбинацией технологий (разные оракулы, встроенные AMM, задержки, мониторинг). Полностью убрать оракулы (как централизованные сущности) из DeFi пока не удалось, но ряд проектов экспериментирует с “oracle-less” концепциями, где возможно. В остальных случаях задача – сделать системы <em>стойкими к неправильным данным</em> (resilient to oracle failures). К этому призывают аудиторы и исследователи безопасности: аудит смарт-контрактов теперь обязательно включает раздел <strong>“Oracle &amp; Price Feed Analysis”</strong>, где проверяется, учтены ли описанные выше меры. Некоторые DAO нанимают специальные <em>Risk Officer</em> или команды, следящие за качеством оракулов и рыночной конъюнктурой, чтобы вовремя предлагать изменения параметров (например, снижение LTV для опасных активов). Митигация oracle-рисков стала коллективным делом сообщества, где участвуют и разработчики инфраструктуры (Chainlink и др.), и сами протоколы, и даже пользователи (которые могут голосовать за соответствующие пропосалы в DAO).</p><h2 id="h-vyvody-i-rekomendacii" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Выводы и рекомендации</h2><p><strong>Оракулы остаются одним из ключевых системных рисков DeFi.</strong> Несмотря на прогресс в технологиях (таких как Chainlink) и горькие уроки прошлых атак, полностью устранить угрозу манипуляции данными невозможно. Каждый новый эксплойт подтверждает: <em>доверие к внешней информации – уязвимость по умолчанию</em>. В то же время, без оракулов немыслимо большинство DeFi-приложений. Это своеобразный “орокульный трилемма”: нужно обеспечить безопасность, децентрализацию и актуальность данных одновременно, что крайне сложно. Ниже суммируем основные выводы и дадим рекомендации разным участникам экосистемы:</p><ul><li><p><strong>Для DAO и управляющих сообществ:</strong> при листинге новых залоговых активов или запуске продукта учитывайте <em>oracle-risks</em> наравне с техническими рисками. Требуйте от команд обоснования: откуда берётся цена, что будет при экстремальных рынках, не сможет ли злоумышленник этим сыграть. Желательно иметь комитет по рискам, который мониторит здоровые параметры протокола (например, ежедневные отчёты о отклонении цен, объёмах торгов базовых активов и т.д.). В решениях управления закладывайте консерватизм: <strong>не принимайте в залог токены с низкой ликвидностью или собственные governance-токены</strong>, без крайней необходимости. Если принимаете – ставьте очень низкое максимальное кредитное плечо (LTV) и высокие штрафы при ликвидации. Рассмотрите возможность страхования от экстремальных случаев (через DeFi-страховки либо создание резервного фонда).</p></li><li><p><strong>Для команд разработчиков DeFi-протоколов:</strong> на этапе дизайна архитектуры уделите особое внимание модулю оракула. Используйте <strong>несколько источников</strong> цены, по возможности – независимых. Внедряйте sanity-check логику: любые необычные изменения цены должны хотя бы логироваться, а лучше – временно блокировать чувствительные действия до дополнительной проверки. Планируйте систему управления такими паузами (в идеале – через мультисиг или быстрое голосование DAO, чтобы не было единоличного контроля, но и не затягивалось решение). Обязательно покройте тестами и симуляциями сценарии oracle-failure: что если цена придёт = 0? = 100x внезапно? Проверьте, нет ли где-то в коде предположения о границах цен, которое может вызвать сбой (переполнение, деление на ноль и т.п.). Привлекайте аудиторов с экспертизой в экономической безопасности, не ограничивайтесь только проверкой кода. И, конечно, интегрируйте проверенные решения: <strong>Chainlink или аналоги там, где возможно</strong>, вместо самодельных костылей. Если пишете свой оракул – проведите отдельный аудит этого компонента. Учтите опыт других: публичные пост-мортемы (Scream, Mango, Inverse и т.д.) – бесценный источник информации о том, чего <em>не</em> стоит делать.</p></li><li><p><strong>Для аудиторов и исследователей безопасности:</strong> развивайте методики анализа оракульных рисков. При аудите смарт-контрактов всегда проверяйте: какой оракул используется, есть ли fallback, что происходит при экстремальных значениях. Рекомендуйте заказчикам внедрять описанные выше best practices (мультифиды, лимиты, паузы, мониторинг). Особое внимание уделяйте тестированию с флеш-кредитами и манипуляциями цен – сейчас существуют инструменты для симулирования подобных атак, используйте их. Пишите публичные отчеты и кейсы: сообщество должно учиться на ошибках. Помните, что безопасность DeFi – это не только формальная верификация, но и оценка <em>экономической устойчивости</em>. Если протокол идеален в коде, но у него заложена финансовая дырка через оракул – это такой же критичный баг, и аудит должен на это указывать.</p></li><li><p><strong>Будущие угрозы и развитие:</strong> по мере роста DeFi мы можем ожидать появления новых видов атак на оракулы. Например, атаки на сами сети оракулов (DDoS на узлы Chainlink, попытки подкупа валидаторов) – пока их не было, но в теории крупные игроки могут пробовать. Также появление все большего числа <em>реальных активов on-chain</em> (Real World Assets) потребует оракулов для курсов, процентных ставок, индексов – здесь риски еще выше, т.к. манипуляции могут исходить из офлайн-мир (подделка отчетности, сговор оценщиков). DAO, входящие в RWA, должны быть особо осторожны в выборе источников данных и юридических гарантий. Ещё одна зона внимания – <strong>кросс-чейн оракулы и мосты</strong>: данные, передаваемые между сетями, по сути выполняют роль оракула состояния другой цепи. В истории уже были взломы мостов на сотни миллионов, и компрометация кросс-чейн сообщения может аналогично привести к неверным данным (пример: взлом моста может передать ложную информацию о заверенной сумме средств). Развитие стандартов вроде Chainlink CCIP и LayerZero направлено на решение этой проблемы, но аудиторам стоит рассматривать мосты также с точки зрения oracle-risk.</p></li></ul><p><strong>Вывод:</strong> оракулы – жизненно важный компонент DeFi, и обращаться с ними надо соответственно. Нельзя рассматривать оракул как «черный ящик» или данность: это такая же часть протокола, которая должна проектироваться, тестироваться и защищаться на всех уровнях. Лучшей стратегией будет принцип <strong>Defense in Depth</strong>: даже если один слой данных скомпрометирован, другой поймает проблему. DeFi-сообщество уже многое усвоило: переход на агрегаторы вроде Chainlink, отказ от отдельных уязвимых практик. Однако успех отрасли в будущем во многом зависит от способности решить «оракульную проблему». Необходимо продолжать исследования, делиться знаниями и инвестировать в новые технологии оракулов. Только так децентрализованные финансы смогут обеспечить и автономность, и доверие – от кода смарт-контрактов до данных, на которых этот код основывается. Повышенное внимание к оракулам – залог того, что <strong>истории вроде Scream или Mango не повторятся</strong>, или по крайней мере будут вовремя локализованы, не подрывая доверие ко всей экосистеме. Каждый участник – от разработчика до инвестора DAO – несёт часть ответственности за это, и вооружившись лучшими практиками, DeFi-сообщество сможет превратить оракулы из “слабого звена” в прочный фундамент новой финансовой архитектуры.</p><p><strong>Источники:</strong> Использованы открытые аналитические отчёты, в том числе CertiK, исследования Chainalysis, материалы CryptoSlate, Unchained и других изданий для описания конкретных инцидентов, а также официальные комментарии участников (Marc Zeller, Andre Cronje и др.).</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
            <enclosure url="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/3f2d8da922d3ffa2d8bcafb19aa5ca3a6539adc86d74692752045fc8b13e8ecf.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[The Infrastructure Standoff 2: Curve’s 2nd DNS Hack]]></title>
            <link>https://paragraph.com/@defi-in-security/the-infrastructure-standoff-2-curve-s-2nd-dns-hack</link>
            <guid>cQlN8IgE07Ki0AmeJKFC</guid>
            <pubDate>Sat, 31 May 2025 13:13:47 GMT</pubDate>
            <description><![CDATA[Recap: The BadgerDAO Frontend CompromiseIn late 2021, DeFi platform BadgerDAO suffered a devastating frontend attack that bypassed its smart contracts entirely. Hackers infiltrated Badger’s cloud infrastructure – specifically, a Cloudflare API key was secretly compromised – and injected malicious JavaScript into the user interface. This rogue code prompted users to sign fraudulent transactions, ultimately draining approximately $120 million worth of crypto from BadgerDAO users. The incident u...]]></description>
            <content:encoded><![CDATA[<h2 id="h-recap-the-badgerdao-frontend-compromise" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Recap: The BadgerDAO Frontend Compromise</h2><p>In late 2021, DeFi platform BadgerDAO suffered a devastating frontend attack that bypassed its smart contracts entirely. Hackers infiltrated Badger’s cloud infrastructure – specifically, a Cloudflare API key was secretly compromised – and injected malicious JavaScript into the user interface. This rogue code prompted users to sign fraudulent transactions, ultimately draining approximately $120 million worth of crypto from BadgerDAO users. The incident underscored how even a secure smart-contract protocol can be betrayed by weaknesses in web infrastructure. BadgerDAO’s team confirmed that no on-chain code was hacked; instead, the attacker exploited a centralized dependency (a Cloudflare application service) to compromise the UI. In response, BadgerDAO froze its front end, patched the Cloudflare exploit, rotated API keys, and brought in cybersecurity experts to investigate. The fallout was severe – beyond the immediate financial loss, user trust was shaken as the community realized that DeFi <strong>interfaces</strong> can be as critical as DeFi <strong>smart contracts</strong> when it comes to security.</p><p>This BadgerDAO episode (covered in our previous article) served as a wake-up call about frontend and DNS security in DeFi. Unfortunately, it was not an isolated case. Other projects soon encountered similar “infrastructure hacks.” One of the most notable was Curve Finance, which has now faced DNS hijacking attacks <em>twice</em> (in 2022 and again in 2025), echoing many of the same themes seen in Badger’s compromise. Below, we dive into Curve’s second DNS hijack incident – how it unfolded, how it was addressed, and what it means for the industry’s frontend resilience.</p><h2 id="h-curve-finances-second-dns-hijacking-incident" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Curve Finance’s Second DNS Hijacking Incident</h2><p><strong>When Users Knew Something Was Wrong:</strong> On May 12, 2025, users of Curve Finance began to suspect trouble when the platform’s website started behaving abnormally. Reports quickly surfaced on social channels – particularly in Curve’s official Telegram group and on X (formerly Twitter) – that the <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://Curve.fi"><strong>Curve.fi</strong></a> site was redirecting or prompting unexpected wallet requests. Around 20:55 UTC, Curve’s team publicly sounded the alarm. The official Curve Finance X account posted a stark warning: “Seems like <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://curve.fi">curve.fi</a> DNS might be hijacked. Don’t interact!”. This message, shown below, immediately alerted users that the frontend had likely been compromised:</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/4c48a92f534fcde99288c3d22a0061728645badc17f8188cfbac5aa428cf3189.png" alt="Curve Finance’s official X (Twitter) account warning users on May 12, 2025 about a suspected DNS hijack. In follow-up replies, the team confirmed the site was resolving to the wrong server IP, indicating a DNS compromise. " blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">Curve Finance’s official X (Twitter) account warning users on May 12, 2025 about a suspected DNS hijack. In follow-up replies, the team confirmed the site was resolving to the wrong server IP, indicating a DNS compromise.</figcaption></figure><p>Within minutes of that tweet, Curve administrators and community moderators were amplifying the message across channels. In Telegram, admins reiterated the warning, urging everyone to <strong>avoid using the website</strong> until further notice (much as they did during the 2022 incident). On Discord, the team opened support threads to handle user reports. Decentralized finance moves fast, and so do its users – by the time the Curve team broadcast the alert, many community members had already been pinging each other about issues. Some users noticed that the Curve website’s interface was unresponsive or “off” – it turned out the attackers had replaced the usual UI with a static decoy page (essentially a screenshot of the real app) containing a single malicious link. Others with security know-how began checking the domain records and observed that <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://curve.fi"><strong>curve.fi</strong></a> was no longer resolving to Curve’s legitimate server. This crowdsourced vigilance meant that within minutes, thousands of users were aware that Curve’s front door had been compromised.</p><p><strong>Community Alerts and Monitoring:</strong> Notably, external security watchers played a role in detecting and confirming the attack. On-chain security firm Blockaid, for example, spotted unusual activity tied to Curve’s frontend and immediately speculated that a <strong>“potential frontend attack”</strong> was underway. Blockaid warned users not to sign any transactions on Curve and stayed in communication as the situation developed. Members of the broader DeFi community on X also flagged the issue as soon as suspicious transactions surfaced – much as they had done during Curve’s first DNS incident in 2022. In that 2022 case, it was a few vigilant users who first noticed funds being siphoned and raised the alarm, prompting Curve to shut down its UI before more damage was done. This time around, the combination of community alerts, security bots, and quick official confirmation helped to limit user exposure. (It also helped that the attackers’ fake page was poorly crafted – one researcher noted “the hackers barely even tried. They just replaced the site with a clickable screenshot and a drainer link,” and remarked it could have been <em>much</em> worse with a more convincing setup.)</p><p><strong>Curve Team’s Response and Discovery:</strong> The Curve core team treated the situation as an emergency infrastructure breach. According to a post-incident timeline provided by Curve, they <strong>discovered the exploit around 21:20 UTC</strong> – roughly 25 minutes after it began – and immediately initiated their incident response plan. First, they broadcast warnings on all official channels (as noted above). Next, they worked to contain the damage at the DNS level: realizing that the <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://curve.fi"><strong>curve.fi</strong></a> domain was pointing to a rogue IP address, Curve’s engineers contacted the domain registrar and also <strong>redirected the </strong><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://curve.fi"><strong>curve.fi</strong></a><strong> nameservers to neutral servers</strong> as a stop-gap. This effectively took the compromised site offline for many users, halting the phishing in progress by making <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://curve.fi">curve.fi</a> unreachable while fixes were underway. Simultaneously, Curve <strong>brought up an alternative interface at</strong> <strong>curve.finance</strong>, a domain that had not been affected. Within hours, they announced that the new <strong>Curve.finance</strong> site was the official frontend going forward, as the team decided to permanently abandon the old <strong>.fi</strong> domain for safety.</p><p>Curve’s quick switch to <strong>Curve.finance</strong> was necessitated by a frustrating obstacle: the <strong>.fi</strong> registrar was slow to respond to the emergency. The compromised <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://curve.fi">curve.fi</a> domain remained under hacker control for several hours because Curve’s registrar (iwantmyname) did not immediately take action despite urgent requests. Curve’s team publicly criticized this delay, calling the response time “totally unacceptable” and emphasizing the need to <strong>wrest control back</strong> from the attackers quickly. Eventually the registrar intervened – the <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://curve.fi">curve.fi</a> domain was frozen (locked from any changes) and traffic fully disabled. But by then, the Curve team had already shifted focus to the new domain and restoring user confidence there.</p><p><strong>What Actually Happened (Technically):</strong> As details emerged, it became clear that this was a classic <strong>DNS hijacking</strong> at the registrar level. In non-technical terms, the attackers had managed to access Curve’s domain settings and change the DNS records so that <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://curve.fi"><strong>curve.fi</strong></a> no longer pointed to Curve’s real servers. Instead, users were being sent to an IP address controlled by the hackers, where a <strong>clone of the Curve website</strong> awaited. This fake site was visually identical to the real Curve app, but its sole purpose was to trick users into signing wallet transactions that would drain their funds (or even to steal seed phrases via fake pop-ups, as security analysts noted). Importantly, Curve’s smart contracts and on-chain liquidity pools were never touched – the attack was <strong>limited to the Web2 layer (DNS)</strong>, meaning the protocol’s funds and code remained secure. Curve’s team reaffirmed this in communications, stating that all smart contracts were safe and that <strong>“no sign of a compromise on our side”</strong> was found in backend systems. They pointed out that robust security (strong passwords and 2FA) was already in place on their accounts – suggesting the attackers may have breached the registrar itself or found a novel way in, rather than simply guessing Curve’s credentials. (In the 2022 incident, Curve similarly concluded that the DNS provider <strong>iwantmyname</strong> was likely hacked on its side, indicating the attackers bypassed Curve’s own security measures by targeting the infrastructure provider).</p><p>Curve Finance’s administrators have promised a full post-mortem report on this second hijack, which should shed more light on the exact vulnerability exploited. As of this writing, preliminary reports suggest the attackers gained registrar access (how exactly remains under investigation) and were able to modify DNS records at around 20:55 UTC on May 12. Certificate records indicate that the hackers likely obtained a TLS certificate for the fake site as well, allowing the fraudulent Curve clone to use HTTPS without browser warnings – a common step in such attacks. (Had Curve used certain DNS security features like CAA or DNSSEC, this certificate issuance might have been harder, a point we’ll revisit in the countermeasures section.) The attack was mitigated by roughly 23:00 UTC once <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://curve.fi">curve.fi</a> was taken offline and the new domain was in place.</p><p><strong>Impact and Aftermath:</strong> Fortunately, the May 2025 hijack appears to have caused <em>less</em> financial damage than Curve’s first DNS hack in 2022. In that earlier August 2022 incident, users who interacted with the fake site lost about <strong>$570,000</strong> worth of cryptocurrency within a few hours. (Over $450K of that was later frozen or recovered with help from exchanges, but the shock was enough to rattle DeFi circles.) The 2025 hijack’s losses have not been fully disclosed, but anecdotal reports suggest they were limited – possibly a few thousand dollars – because the alarm was raised quickly and the fake site was relatively crude. The <strong>psychological</strong> impact, however, was significant. CRV (Curve’s governance token) dropped over 7% on the news, as investors reacted to yet another security failure on a critical DeFi platform. The incident came just a week after Curve’s official X (Twitter) account itself had been hacked on May 5 (an attacker briefly took over the @CurveFinance handle to post phishing links). Suffering back-to-back social engineering attacks – first on its social media, then on its DNS – put Curve in an uncomfortable spotlight.</p><p>In response, Curve’s team has doubled down on security upgrades. Immediately after the second DNS hijack, they <strong>permanently moved</strong> to the new <strong>curve.finance</strong> domain, explicitly citing “prolonged downtime and limited support” from the old <strong>.fi</strong> registrar as reasons to never go back. They froze updates on the .fi domain to prevent any further abuse. A spokesperson from Curve assured users that internal controls (passwords, 2FA, etc.) had not been bypassed and that the exploit was isolated to the DNS layer. Going forward, Curve stated it is <strong>enhancing registrar-level security and exploring alternative registrars</strong> with stronger protections. They are also actively investigating <strong>decentralized front-end options</strong> (like using IPFS or Ethereum Name Service) to reduce reliance on traditional DNS infrastructure. In fact, Curve is collaborating with the ENS community on initiatives to enable native browser support for <strong>.eth</strong> domains, which could allow a “DNS-free” access path for users in the future. In short, Curve’s second DNS fiasco has prompted a comprehensive re-evaluation of its front-end architecture.</p><p>Before discussing potential solutions to these recurring issues, let’s compare the Curve and BadgerDAO cases to understand common patterns.</p><h2 id="h-patterns-in-defi-frontend-vulnerabilities-curve-vs-badgerdao" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Patterns in DeFi Frontend Vulnerabilities (Curve vs. BadgerDAO)</h2><p>The BadgerDAO and Curve attacks, while exploiting different entry points (a cloud API vs. a DNS registrar), highlight a similar pattern: <strong>DeFi projects remain dependent on centralized web infrastructure</strong>, which can be a single point of failure. In both cases, the protocol’s decentralized smart contracts were untouched – Badger’s vaults and Curve’s liquidity pools were secure – yet users still lost funds because the interface that connects users to those contracts was compromised. This underscores a critical “trust gap” in DeFi: even if back-end code is trustless, the front-end that most users rely on is not trustless at all.</p><p>Both incidents demonstrate how attackers are increasingly <strong>shifting focus from protocol code to infrastructure and user-facing systems</strong>. As one report noted, these hacks show that hackers will target the “weakest link,” which is often the web2 components like DNS, hosting, or social media, rather than the smart contracts themselves. In the months surrounding Curve’s DNS hack, several other crypto platforms saw DNS or social account hijacks, indicating a broader trend of targeting operational infrastructure over on-chain vulnerabilities. The appeal for attackers is clear: why try to defeat audited smart contracts when you can simply trick users into giving you permission to their assets?</p><p>Another commonality is the <strong>importance of real-time communication</strong> during such attacks. Both BadgerDAO and Curve were able to limit damage by quickly alerting their communities. In Badger’s case, once they realized the frontend was malicious, they halted all contracts and warned users, but by then a lot of damage was done due to the speed of the attack. Curve, during both DNS incidents, immediately used Twitter, Telegram, and Discord to broadcast warnings. Fast communication can save users from falling prey to an ongoing attack, especially in DNS hijacks where the <em>only</em> indication of fraud might be a subtle URL or certificate discrepancy that many users miss. The lesson is that DeFi teams need robust monitoring and incident response plans for their frontends, just as they have for their smart contracts.</p><p>Finally, these cases highlight that <strong>recovery is difficult</strong> once such an attack occurs. Even though some of Curve’s stolen funds were recovered with the help of exchanges freezing assets, and BadgerDAO later worked on reimbursing users, prevention is far preferable. Unlike a smart contract exploit where a bug can be patched, a DNS or frontend attack often stems from weaknesses in human or organizational processes (e.g. API keys, account security, registrar reliability) – plugging those holes requires a mixture of technical and procedural fixes. In the next section, we evaluate several proposed countermeasures that could make DeFi frontends more resilient against these “infrastructure attacks.”</p><h2 id="h-hardening-defi-frontends-eight-countermeasures" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Hardening DeFi Frontends: Eight Countermeasures</h2><p>In light of repeated DNS and frontend attacks, the crypto community has brainstormed various measures to bolster the <strong>resilience</strong> of DeFi user interfaces. Below we evaluate eight such proposed countermeasures, discussing how each could help and what trade-offs they entail:</p><ol><li><p><strong>Multiple Domains (Different Registrars &amp; TLDs):</strong> One idea is to maintain <strong>redundant domain names</strong> on separate top-level domains and with different registrars. This means if one domain is hijacked or goes down, users can quickly switch to an alternate official domain. Curve actually had a glimpse of this strategy: in the 2022 attack, they directed users to <strong>curve.exchange</strong> as a fallback while resolving the <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://curve.fi"><strong>curve.fi</strong></a> issue. Likewise, after the 2025 hack they permanently shifted to <strong>curve.finance</strong>. By registering domains in different TLD zones (e.g. .fi, .com, .xyz) and using reputable, separate registrars for each, a project reduces the risk that a single point of failure takes them completely offline. Even if an attacker compromises one registrar, the others remain unaffected. However, this approach only works if users <strong>know about the alternate domains</strong> <em>and trust them</em>. Projects would need to publicize their official mirrors well in advance (see point 6 on social posts) to avoid confusion. There’s also overhead in maintaining multiple domains securely (renewing them, securing each account with 2FA, etc.). Still, this redundancy can be a lifesaver. It creates an “insurance policy” – for example, had Curve’s team not controlled curve.finance already, spinning up a new domain during the crisis would have been slower and harder. Many projects are now considering reserving extra domains proactively to prepare for such scenarios.</p></li><li><p><strong>Adding CAA DNS Records:</strong> DNS CAA (Certification Authority Authorization) records are a security measure to harden the SSL/TLS certificate issuance for a domain. In essence, a CAA record lets a domain owner specify <strong>which certificate authorities (CAs) are allowed to issue certificates</strong> for their domain. For example, a project can say “only Let’s Encrypt and DigiCert can issue certs for <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://mydomain.com">mydomain.com</a>” – so if an attacker tries to get a certificate from another CA, that CA should refuse. Why does this matter? In a DNS hijack, the attacker will often attempt to obtain a valid HTTPS certificate for the hijacked domain (to avoid browser warnings). CAA records make that harder by limiting the universe of CAs they can use and providing notification if an unauthorized request is made. In Curve’s case, if they had strict CAA records, an attacker might have been unable to silently get a certificate from, say, a lesser-known CA. The attack could still proceed (attackers could use an allowed CA or may have compromised the registrar enough to edit CAA records too), but CAA raises the bar. It’s a relatively simple, low-cost defense that can prevent <em>some</em> phishing scenarios or at least generate audit logs (via CAA’s reporting) if someone tries to abuse certificate issuance. However, CAA is not foolproof – a determined attacker who has fully hijacked DNS could simply modify the CAA record as well. Still, many security experts recommend CAA as part of a defense-in-depth strategy to prevent unnoticed certificate mis-issuance.</p></li><li><p><strong>Deploy the Frontend on ENS + IPFS:</strong> To eliminate dependence on traditional DNS entirely, DeFi projects can use the <strong>Ethereum Name Service (ENS)</strong> and content-addressable storage like <strong>IPFS</strong> for their frontends. ENS is a decentralized naming system on Ethereum (e.g. resolving <strong>curve.eth</strong>), and it can be used to point to content on IPFS. IPFS (InterPlanetary File System) allows hosting the static web app code in a distributed way. The combination means users can access the app via a URL like <code>curve.eth</code> (or a gateway like <code>curve.eth.limo</code> which fetches from IPFS) instead of a DNS-based URL. The advantage is that <strong>ENS names are secured by the blockchain</strong>, not by a centralized registrar, and IPFS content is tamper-evident (addressed by hash). This drastically reduces the attack surface for domain hijacks – there is no traditional DNS to hijack. Curve’s team has indicated they are now exploring such decentralized front-end options, and they are advocating for better browser support of ENS links. In practice, some DeFi apps (like Uniswap) already provide an IPFS-hosted interface accessible via ENS or dedicated gateways. The downside to this approach is primarily <strong>usability</strong>: average users may not know how to use an ENS domain or may be uncomfortable without the familiar “.com” or “.fi”. There’s also the need to keep the IPFS content updated with every frontend change (though this can be automated in deployment pipelines). Additionally, while ENS can’t be hijacked via DNS, it introduces the need to secure the ENS owner keys – a new kind of risk (if someone compromises the team’s ENS controller keys, they could repoint the name). Nonetheless, ENS+IPFS is widely seen as a promising path to <strong>trustless frontends</strong>, and incidents like Curve’s have accelerated calls to adopt these technologies.</p></li><li><p><strong>Hosting a Tor .onion Mirror:</strong> Another path to bypass DNS entirely is providing an official <strong>Tor hidden service (onion)</strong> address for the DApp frontend. Onion addresses are self-authenticating and do not rely on DNS hierarchies – the “name” of an onion site is derived from its public key. By accessing Curve (or any DeFi app) via a Tor browser and a <code>.onion</code> URL, users could be sure they are connecting to the intended server run by the project, assuming the onion address is correct and verified. Even if an attacker hijacks the regular DNS, they cannot easily hijack the Tor address because that would require stealing the private key for the onion service. Some cryptocurrency services already offer onion sites for censorship-resistance and security (for instance, major exchanges have onion mirrors to serve users in restrictive regions). For DeFi, an onion site could serve as a <strong>high-security fallback</strong> – likely used by fewer users, but available in emergencies or for those who prioritize security. The challenges here: users must use the Tor network (which can be slower and is blocked in some corporate environments), and the project must make the community aware of the official onion address (perhaps publishing the onion fingerprint in documentation or tweets). Additionally, the frontend must be configured to work over Tor, which may involve some tweaks (e.g. avoiding clearnet API calls that would leak out of Tor). Despite being a niche solution, a Tor mirror would directly counter DNS hijacks by providing an access method completely independent of DNS and CA infrastructure. It’s a strong option for resilience, appealing especially to power-users and security-conscious community members.</p></li><li><p><strong>Telegram Mini-App Interface:</strong> Given the prevalence of Telegram in the crypto community, one innovative idea is to build a <strong>Telegram Mini App</strong> for the DeFi platform. Telegram’s mini-app platform allows projects to embed lightweight web apps within the Telegram interface (often used for games or tools). In this context, Curve could develop a mini-app that lets users perform basic functions (view balances, swap tokens, add liquidity, etc.) inside Telegram’s app, without visiting an external browser at all. The security benefit is that users would be interacting with Curve through a trusted channel (the official Telegram bot/app) – DNS hijacking is not an issue because Telegram itself handles the addressing. The mini-app’s content is served via Telegram’s infrastructure, and while that is still centralized, it’s much harder for a random attacker to compromise than an isolated domain registrar. Essentially, the trust shifts to Telegram’s platform and the integrity of Curve’s mini-app code. This approach could also mitigate phishing, since users wouldn’t have to type a URL – they’d just open Telegram and use the verified Curve app interface. There are caveats: A mini-app may not support all advanced features of the web app initially, and users must trust the Telegram closed-source environment to some degree. Also, developing and maintaining a parallel interface is extra work for the team. However, many DeFi users are already on Telegram, so this could greatly lower the barrier for accessing a “known good” interface. Over time, a Telegram mini-app could grow in functionality and serve as an official fallback if the main site is ever down or suspect. It leverages the fact that Telegram chats (especially official announcement channels) are a primary way teams disseminate urgent messages – by having an app right there, the team can direct users: “use our Telegram mini-app for now” in case of an attack. This is a relatively novel countermeasure, but it aligns with the broader idea of <strong>multiplatform frontends</strong> to avoid total reliance on any single web domain.</p></li><li><p><strong>Auto-Sharing Official Mirror Lists:</strong> A simpler but important practice is to <strong>consistently share and update the list of official web gateways</strong> in all communications. This means every major social post, blog update, or pinned message should remind users of the project’s legitimate domains (e.g. “Our official sites are curve.finance, <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://curve.fi">curve.fi</a> (currently down), curve.onion, and our ENS curve.eth”). By doing this proactively, users are less likely to be caught off-guard by a sudden domain change or to fall for impostor sites. In the chaos of a DNS hijack, scammers often spin up lookalike domains or social accounts to further confuse users. If the community has ingrained knowledge of the <em>exact</em> mirrors and alternatives, they can more easily avoid fakes. During Curve’s May 2025 incident, once the team brought up <strong>curve.finance</strong> as a new domain, they blasted that information on Twitter and Telegram so users knew where to safely go. Imagine if those alternative links were already in everyone’s bookmarks or linked in Curve’s Twitter bio beforehand – the switchover could have been even smoother. The takeaway is that projects should treat their domain list as part of their identity, and <strong>continuously publish it</strong>. For example, having a command in Telegram/Discord where the bot replies with “Official links:” and lists them, or a standing section in newsletters repeating the mirrors. This reduces reliance on frantic communication during an attack; users will already have reference points. Of course, maintaining this list means updating it whenever new mirrors (like an ENS or onion) are added, and ensuring all team communications use those official links (to train users to recognize them). It’s an operational step more than a technical one, but it strengthens the human layer of phishing defense.</p></li><li><p><strong>Distributed APIs and Third-Party Access Providers:</strong> Another countermeasure is to decouple the <strong>data and transaction layer</strong> from the project’s own frontend by leveraging third-party API services. For instance, some wallets and aggregator apps use services like <strong>Moralis Web3, Infura, Alchemy,</strong> or others to fetch data and even to execute contract calls on behalf of the user. If a DeFi project ensures that its contracts are easily accessible through well-known public APIs or SDKs, then users have alternatives to the official frontend. In practice, this means if the website is down or compromised, users (especially advanced ones) can switch to using a wallet’s built-in DApp browser, a command-line tool, or a community-built interface that interacts with the same contracts via those APIs. How does this help security? It doesn’t prevent a DNS hack, but it <strong>mitigates user impact</strong> by not making them solely reliant on one website. In Curve’s case, even while their frontend was under attack, the <strong>smart contracts continued to operate</strong> – in fact, Curve processed over $400 million in on-chain volume during the DNS outage via direct contract calls and aggregators. Many users with knowledge simply went to other platforms (like Zapper, Zerion, or Etherscan’s Write Contract feature) to interact with Curve contracts directly. By encouraging use of distributed access providers (and perhaps providing an official API endpoint as a fallback), DeFi projects can ensure there’s <em>no single web portal</em> whose compromise would completely halt user ability to transact. Another angle is that if the official frontend is using a third-party API for critical actions, an attacker who only hijacks the static site might not easily redirect those API calls to malicious ones without also defeating additional authentication. However, reliance on third-party APIs can introduce new trust issues and dependencies (if those services have outages or if they were compromised, that’s another problem). So this measure is more about <strong>resilience and availability</strong> than pure security. It complements the others by giving savvy users multiple paths to the protocol.</p></li><li><p><strong>Use Cloud-Native Domains &amp; Multi-Cloud Mirrors:</strong> Instead of (or in addition to) running a website on a custom domain, projects can leverage domains provided by big cloud platforms that have extremely robust security. For example, an app deployed on Google App Engine can be accessed at <code>*.appspot.com</code>, and a static site on GitHub Pages is available at <code>*.github.io</code>. These domains are managed by Google and GitHub respectively, which means an attacker would have to breach those companies’ infrastructure (or the project’s account) to hijack the DNS – a much more difficult feat than hacking a small registrar. By hosting a verified mirror of the frontend on such domains, teams add an extra layer of protection. If <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://curve.fi"><strong>curve.fi</strong></a> is down, users might go to a URL like <code>curve.web.app</code> (if hosted on Firebase) or <code>curve.pages.dev</code> (if on Cloudflare Pages), etc. Each of these uses the provider’s globally secured domain. During an incident, the team could quickly announce: “Use our verified mirror on <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://XYZ.cloudprovider.com">XYZ.cloudprovider.com</a>.” Because these platforms often integrate SSL and security by default, the attack surface is reduced (no separate DNS to manipulate apart from the platform itself). Additionally, maintaining <strong>multi-cloud deployments</strong> – e.g. one on AWS, one on GCP, one on Cloudflare – means even if one provider has an issue or the project’s account is compromised on one platform, the others are unaffected. This strategy is about <strong>diversifying hosting and domain control</strong> under the assumption that not all platforms will fail at once. The downside is complexity and cost: deploying and updating across multiple cloud providers requires DevOps effort, and the user experience of non-standard URLs might be confusing if not well-publicized. There’s also a small risk that users might be phished by fake “mirror” URLs – hence the importance of point #6 (always publish the exact official mirrors). Despite these challenges, some security-focused projects adopt this approach. It aligns with the general principle of avoiding a single point of failure. In the context of DNS attacks, using the battle-hardened infrastructure of companies like Google, Cloudflare, or Amazon for fallback addresses can significantly raise the attacker’s burden.</p></li></ol><p><strong>Closing Thoughts:</strong> None of these countermeasures alone can guarantee safety, but <strong>layered together, they dramatically improve front-end security and resilience</strong>. As Cointelegraph noted in the wake of Curve’s hack, bridging the gap between decentralized backends and centralized frontends requires a multi-layered approach. Projects must secure their domain registrars (with 2FA, registrar locks, etc.), consider decentralized hosting (ENS/IPFS), implement technical DNS safeguards (DNSSEC, CAA), and have operational plans for rapid user communication and failover. Equally important is user education: even the best infrastructure can falter if users aren’t aware of alternate access methods or how to verify the legitimacy of a site. In the evolving landscape of DeFi, the <em>infrastructure standoff</em> between developers and attackers continues. The second Curve DNS hijack shows that attackers will repeat tactics that work – it’s on projects now to learn from these incidents and fortify the weakest links. By adopting measures like the ones above, DeFi platforms can make it exponentially harder for the next DNS hijacker or web-interface hacker to succeed, thereby protecting their users and the ecosystem’s credibility.</p><p><strong>Sources:</strong> The information in this article is backed by incident reports and statements from the affected projects and security researchers. For instance, CoinDesk and Cointelegraph reported detailed breakdowns of the BadgerDAO hack and Curve’s 2022 DNS hijack, while updates from May 2025 (Curve’s own posts and analyses by Cointelegraph, CryptoSlate, and others) chronicle the second Curve hijacking and its resolution.</p><p><strong>These events underscore a crucial lesson: decentralization doesn’t end at the smart contract – to truly safeguard user funds, the community must also decentralize and secure the front-end gateways into DeFi.</strong></p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
            <enclosure url="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/56bbe7fb07eaa60f82fbeed9f478f090d6d25e680c8c791a595d2c3da2f3ef15.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Why Crypto Payment Systems Fail: Technical Vulnerabilities and Resilient Design]]></title>
            <link>https://paragraph.com/@defi-in-security/why-crypto-payment-systems-fail-technical-vulnerabilities-and-resilient-design</link>
            <guid>JTAg8oupmenADfS00JTO</guid>
            <pubDate>Wed, 21 May 2025 20:05:36 GMT</pubDate>
            <description><![CDATA[Cryptocurrency payment gateways have enabled merchants to accept digital assets, but many such systems suffer from reliability problems and operational failures. This whitepaper analyzes common failure modes in crypto payment infrastructure and examines case studies of Coinify and Coinbase Commerce to illustrate these issues. It also provides a critical assessment of other popular crypto payment solutions – including BitPay, NOWPayments, and BTCPay Server – focusing on their technical and ope...]]></description>
            <content:encoded><![CDATA[<h1 id="h-" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0"></h1><p>Cryptocurrency payment gateways have enabled merchants to accept digital assets, but many such systems suffer from reliability problems and operational failures. This whitepaper analyzes common failure modes in crypto payment infrastructure and examines case studies of <strong>Coinify</strong> and <strong>Coinbase Commerce</strong> to illustrate these issues. It also provides a critical assessment of other popular crypto payment solutions – including BitPay, NOWPayments, and BTCPay Server – focusing on their technical and operational vulnerabilities. Finally, we define the principles of a disaster-resilient “unbreakable” crypto payment architecture and offer detailed recommendations for merchants to achieve high availability, robust <strong>Business Continuity Planning (BCP)</strong>, decentralized operation, and effective fallback mechanisms.</p><h2 id="h-common-failure-modes-of-crypto-payment-systems" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Common Failure Modes of Crypto Payment Systems</h2><p>Crypto payment systems often break down due to a combination of technical and operational weaknesses. Key failure modes include:</p><ul><li><p><strong>Single Points of Failure &amp; Centralization:</strong> Many gateways rely on centralized infrastructure (cloud servers, APIs) that can go offline. If the provider’s servers or network connectivity fail, merchants are left unable to process payments. For example, BitPay’s own documentation notes that during a system outage, customers simply <strong>“need to use a different payment method or return later”</strong>. This dependency on a central service with no failover leads to downtime risk. While blockchains themselves are decentralized, <strong>merchant payment platforms often introduce centralized components</strong> (processing APIs, wallet services) – these must be identified and addressed in any continuity plan.</p></li><li><p><strong>Poor Support and Maintenance:</strong> Many crypto payment providers lack responsive support or robust maintenance processes, leading to prolonged issues when problems arise. Coinify is a case in point – merchants have reported opening support tickets that <strong>never received a response</strong>, even after funds were debited from their bank without delivering the crypto. In another report, a user described Coinify’s support as <em>“laughable,”</em> with replies only every few days. Smaller providers can also suffer from weak support; for instance, a merchant testing NOWPayments found the support staff unknowledgeable and slow, taking 5–8 minutes to produce canned answers from an FAQ. He concluded, <em>“they are unable to answer just the simplest questions… I can only imagine how it would go if there is a technical problem”</em>. Such support deficits exacerbate downtime and instill mistrust when critical issues occur.</p></li><li><p><strong>Integration Complexity and Technical Friction:</strong> Adding crypto payments to existing commerce platforms can be technically complex and error-prone. Some gateways introduce non-standard protocols or require specific wallet software, complicating integration. For example, BitPay’s implementation historically used a custom payment protocol (BIP-70) that generated QR codes not as a direct address but as a link to BitPay’s server. Customers who scanned the code with a normal wallet scanner would encounter errors, since <strong>the QR code redirected to BitPay’s website rather than a simple address</strong>. This necessitates special handling (using the camera app or copy-pasting the address) – a confusing extra step for users. Such technical quirks and insufficiently documented APIs increase the integration burden for developers, leading to higher failure rates in deployment.</p></li><li><p><strong>Poor User Experience (UX) for Payers:</strong> If the payment flow is confusing or restrictive, customers may abandon the transaction, nullifying the whole purpose. A common expectation in crypto payments is to see a QR code to scan with any wallet. Systems that deviate from this familiar flow can impede ease of use. Coinbase Commerce is a prominent example: it <strong>requires customers to connect a personal crypto wallet (Coinbase Wallet or MetaMask) before a payment can be made</strong>, instead of simply displaying a QR code/address. This design forces users into a web3-style wallet integration, which <strong>“differs from the usual QR code process”</strong> and can easily confuse payers. Merchants risk losing sales if buyers face extra wallet connection steps or unsupported payment methods. Similarly, <strong>lack of broad wallet compatibility</strong> (e.g. not supporting Lightning Network or certain coins) is a UX failure mode – Coinbase Commerce does not support Bitcoin Lightning payments at all, limiting users to slower on-chain transactions.</p></li><li><p><strong>Regulatory Fragility:</strong> Crypto payment companies operate in a fluid regulatory environment, and reliance on a centralized service exposes merchants to compliance-related disruptions. Providers may suddenly restrict service in certain regions or freeze transactions to comply with laws, catching merchants off-guard. For instance, U.S. regulators fined BitPay for processing payments from sanctioned countries. Such actions compel processors to enforce strict geo-blocking, user identity checks, or sudden policy changes that can interrupt service. Merchants using Coinify have experienced “out of region” errors even when they were in a supported area (likely due to rigid compliance filters), with <strong>accounts getting locked and support not responding to fix it</strong>. In general, a centralized gateway can be a <strong>single point of regulatory failure</strong> – if its license is revoked or it shuts down under legal pressure, all merchants on the platform lose functionality overnight.</p></li></ul><p>These failure modes demonstrate that crypto payment systems are often only as strong as their weakest link – whether technical (infrastructure, integration) or human (support, compliance). Next, we delve deeper into two case studies that highlight these issues in real-world platforms.</p><h2 id="h-case-study-coinify-lack-of-support-and-service-breakdown" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Case Study: Coinify – Lack of Support and Service Breakdown</h2><p>Coinify, a Denmark-based crypto payment processor, has been used by merchants and even integrated into hardware wallet apps. Over time, it has gained a reputation for serious service issues. A critical failure point for Coinify has been its <strong>customer support and reliability</strong>. Numerous users report scenarios where transactions simply never completed and support tickets went unanswered. In one instance, a customer purchased cryptocurrency via Coinify (through a partner service) and never received the coins. <strong>“I opened tickets but they didn’t respond, so I think that I lost my money,”</strong> the user writes, noting Coinify debited the bank account but delivered nothing. Such incidents indicate a breakdown in operational processes (either the trade execution failed or payout was blocked) compounded by nonexistent support to resolve the error.</p><p>Merchants relying on Coinify’s payment gateway have faced similar frustrations. Reviews point out that Coinify’s <strong>payout and transfer processes are unreliable and riddled with issues</strong>, especially across borders. One reviewer described the international bank transfer payout as <em>“not reliable and filled with issues”</em>, and although customer service gave a quick initial response, they <strong>“did not resolve the issue”</strong>, leaving the merchant in limbo. Other users have alleged even more alarming behavior, with Coinify <strong>holding onto large sums and refusing withdrawals</strong>. A user claims that after Coinify’s trading hub “locked” their funds, <strong>“no customer service support”</strong> was available and they were asked to pay an additional fee to release their money. (If true, this suggests either a deeply negligent practice or a potential fraud incident.)</p><p>A consistent theme is the <strong>absence of robust support or escalation paths</strong> for when things go wrong on the platform. Coinify provides no phone support and minimal ticket responsiveness. This lack of support is itself a technical vulnerability: routine software or integration bugs can become catastrophic if not addressed promptly. Merchants have no recourse during outages or service errors, resulting in lost sales and lost trust.</p><p>In effect, Coinify’s case illustrates how a payment system can “fail” not only from pure technology problems, but from operational negligence. Even if the blockchain networks underneath are sound, the platform’s surrounding services (trade engine, bank transfers, customer support) became single points of failure. Once those failed – and without a continuity plan or support responsiveness – the entire payment flow collapsed for affected users. An abandoned support system is as damaging as a crashed server in this context. For merchants, the Coinify story is a cautionary tale about vetting the <strong>service quality and reliability</strong> of a crypto payments provider, not just its technical features.</p><h2 id="h-case-study-coinbase-commerce-wallet-integration-vs-ease-of-use" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Case Study: Coinbase Commerce – Wallet Integration vs. Ease of Use</h2><p>Coinbase Commerce is the cryptocurrency payment solution offered by Coinbase, aimed at online merchants. While backed by a major exchange and brand, it introduced a design choice that arguably hampers the usability of crypto payments for end customers. In an effort to create a <strong>“seamless” on-chain payment experience</strong>, Coinbase Commerce requires the payer to <strong>connect a crypto wallet (such as Coinbase’s own mobile wallet or a MetaMask browser wallet) to the checkout</strong>. Only after this wallet link is established can the customer initiate payment, with the system then communicating the payment details directly to the wallet app.</p><p>In theory, this eliminates manual data entry – the address and amount are passed automatically – but in practice it creates a <strong>walled garden effect</strong>. Customers who simply want to pay by scanning a QR code with <em>their wallet of choice</em> are unable to do so on Coinbase Commerce-powered sites. Unlike traditional crypto gateways that display a QR code (containing a deposit address and exact amount) for any wallet to scan, Coinbase Commerce’s approach assumes a Web3 connection. This <strong>“connect wallet” requirement is a hurdle for many users</strong>, especially those not already using the Coinbase Wallet or MetaMask. It effectively forces new users to go through additional steps (e.g. opening a Coinbase Wallet account or installing MetaMask) at checkout – a moment when any extra friction can lead to cart abandonment.</p><p>From the merchant’s perspective, this design undermines one of crypto’s selling points: universal accessibility. <strong>Ease of use is critical</strong>, and deviating from standard payment flows poses a risk. A crypto payment gateway should ideally accept payments from <em>any</em> wallet that a customer might have. By requiring a specific wallet connection, Coinbase Commerce impedes that universality. Industry reviewers have taken notice; an analysis by CoinCharge flatly concludes: <strong>“The payment process [with Coinbase Commerce] differs from the usual QR code process… nothing should be used that complicates the payment process or confuses the payer.”</strong>. In their view, this system fails the simplicity test and they give a <em>“clear no”</em> to recommending Coinbase Commerce for online stores.</p><p>Coinbase Commerce also has other limitations symptomatic of broader failure modes. It currently <strong>lacks Lightning Network support</strong>, meaning it cannot utilize Bitcoin’s main scalability solution for fast, low-fee transactions. This omission is technically notable: while Coinbase has integrated Lightning into its main exchange, it did not extend it to Commerce. The result is that merchants cannot accept Lightning payments through Coinbase Commerce, putting them at a disadvantage for small or instant Bitcoin payments. Additionally, Coinbase Commerce <em>only</em> settles merchant funds in USDC stablecoin (automatically converting all customer payments to USDC). This reduces volatility risk, but also means merchants who wish to receive and hold the actual cryptocurrency (BTC, ETH, etc.) cannot do so via this platform – a flexibility issue that some might view negatively.</p><p>In summary, Coinbase Commerce’s case shows how <strong>user experience missteps and integration constraints</strong> can cause a crypto payment system to falter despite a strong brand backing. By prioritizing a proprietary payment protocol and specific wallet connections, the system sacrifices the openness and ease-of-use that crypto users expect. For a merchant, this translates to potential lost customers and a narrower funnel of who can successfully pay. A robust crypto payment solution must meet users where they are – which often means offering both the cutting-edge <em>and</em> the familiar paths (web3 <em>and</em> QR codes, on-chain <em>and</em> Lightning, etc.). Coinbase Commerce’s one-size-fits-all onchain wallet connect approach has proven to be a liability in that regard.</p><h2 id="h-limitations-in-other-crypto-payment-gateways-bitpay-nowpayments-btcpay" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Limitations in Other Crypto Payment Gateways (BitPay, NOWPayments, BTCPay)</h2><p>Beyond Coinify and Coinbase Commerce, several leading crypto payment gateways each exhibit failure points that highlight the industry’s challenges. We examine three prominent ones – <strong>BitPay</strong>, <strong>NOWPayments</strong>, and <strong>BTCPay Server</strong> – from a critical standpoint, focusing on downtime risk, support shortfalls, and BCP (Business Continuity Planning) weaknesses.</p><h3 id="h-bitpay-centralized-control-and-downtime-risks" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">BitPay: Centralized Control and Downtime Risks</h3><p>BitPay is one of the oldest cryptocurrency payment processors, known for converting crypto to fiat for merchants. Its centralized architecture, however, introduces classic single points of failure. Merchants using BitPay depend entirely on BitPay’s servers and APIs to create invoices and detect payments. If BitPay’s service goes down – whether due to technical outage or a cyberattack – <strong>all merchant checkouts relying on it are suspended</strong>. BitPay openly acknowledges this risk: if the system is down, the only solution is for the customer to use another payment method or come back later. This is a stark contrast to the decentralized ethos of cryptocurrencies and underlines that BitPay is a <strong>central intermediary</strong>. Any network or database outage on their side directly halts transaction processing for thousands of businesses, with no immediate alternative. Historically, BitPay has also mandated use of specific payment protocols (like BIP-70 in the past), which caused incompatibilities with many wallets and effectively <strong>locked out users whose wallets didn’t support BitPay’s format</strong>. Although BitPay later added compatibility modes, this episode demonstrated how tight control over the payment flow can introduce failures if the ecosystem doesn’t universally adopt the same standards.</p><p>Support and flexibility issues have also plagued BitPay. Being a regulated money transmitter, BitPay requires merchants and sometimes customers to adhere to compliance steps (identity verification for large payments, etc.), and it has in instances frozen transactions pending additional checks. There have been reports of <strong>funds seemingly “lost” or significantly delayed within BitPay’s system</strong>, with customers struggling to get timely support. For example, a user on Reddit sent a large Bitcoin Cash payment to a BitPay invoice that never confirmed correctly; BitPay neither credited the merchant nor promptly refunded the buyer. The frustrated customer said <em>“they never credited me nor will they refund the payment,”</em> even after a week of daily calls and emails. Eventually such issues may be resolved, but the <strong>timeframes involved (days or weeks of no response)</strong> highlight a support capability gap when something goes wrong outside the automated happy path.</p><p>Moreover, BitPay’s need to comply with regulations can trigger abrupt changes or service denials that impact merchants. In 2021, BitPay reached a settlement with U.S. regulators over sanctions compliance failures, having processed transactions from prohibited regions. Consequently, BitPay now geoblocks certain areas and must actively monitor transactions, introducing friction and points of potential failure (e.g. false positives blocking legitimate payments). This <strong>regulatory overhead</strong> is a form of fragility: merchants may wake up to find certain payments blocked or their account under review due to an evolving compliance rule.</p><p>In essence, BitPay’s convenience comes at the cost of <strong>centralized risk</strong>. The company provides valuable services (automatic conversion to fiat, merchant accounting, etc.), but when evaluating it through a failure lens, one finds dependence on BitPay’s uptime, BitPay’s protocols, and BitPay’s compliance status. Without a robust failover or backup (which BitPay does not offer by default), a merchant is exposed to outages that they have no control over – a clear BCP concern.</p><h3 id="h-nowpayments-reliability-and-support-concerns" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">NOWPayments: Reliability and Support Concerns</h3><p>NOWPayments is a newer entrant that markets itself as a simple, non-custodial crypto payment gateway. It supports a wide variety of coins and promises automatic payout of funds to merchants’ own wallets, thus not holding custody by default. This design – if properly implemented – can mitigate some custody risks (e.g., a hack of the provider would not drain merchant funds) and reduces regulatory burden on the provider. However, <strong>non-custodial processing does not by itself guarantee reliability</strong> or continuity. Merchants still rely on NOWPayments’ infrastructure to generate payment addresses and listen for incoming payments. If the NOWPayments platform is offline or its blockchain observers fail, payments could be missed or delayed. The lack of custody might even complicate recovery – for instance, if a transaction was paid but not forwarded to the merchant due to a service crash, manual intervention would be needed to reconcile it once service is restored.</p><p>One of the biggest question marks around NOWPayments is <strong>operational maturity</strong>. As a relatively young company, it has less of a track record, and anecdotal reports suggest issues with support and technical polish. In community forums, users have noted that while NOWPayments offers live chat, the quality of support can be poor. One business owner recounts that support agents seemed to be third-party contractors with minimal knowledge of the system. Basic questions took many minutes to get answered and often were met with copy-pasted text from FAQs, not direct solutions. This raises doubts about how NOWPayments would handle a serious incident – for example, a blockchain fork or an influx of unconfirmed transactions clogging their system. If the front-line support cannot handle “the simplest questions,” confidence is low that they could effectively guide merchants through complex troubleshooting.</p><p>Additionally, being new, NOWPayments may not have a fully robust infrastructure. <strong>Downtime or performance issues</strong> have been reported sporadically by users, though on a small scale (e.g., delays in their WooCommerce plugin confirming payments, which had to be patched). The platform’s adherence to non-custodial flow means each transaction triggers an on-chain transfer to the merchant’s wallet, which could introduce latency or higher fees and complexity (especially if done across many currencies). It also means <strong>no aggregate batching or off-chain scaling</strong> – every payment hits the blockchain, so during network congestion, NOWPayments merchants might suffer delays or higher costs without any alternative path.</p><p>Crucially, NOWPayments does not appear to advertise any <strong>business continuity features</strong> beyond standard redundancy. There’s no mention of an automatic failover gateway or an offline mode. Merchants are not immune to the provider going down. As with others, the merchant’s crypto checkout is only as available as NOWPayments’ systems. If NOWPayments were to shut down (temporarily or permanently), a merchant would have to quickly switch to a different solution or risk failed payments. In summary, while NOWPayments attempts to reduce some risks via a non-custodial model, it still shares many failure modes with centralized gateways: dependence on a single service’s uptime and support effectiveness. Without evidence of strong BCP planning or a long reliability history, merchants should approach it cautiously and have backups in place.</p><h3 id="h-btcpay-server-self-hosting-power-with-operational-challenges" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">BTCPay Server: Self-Hosting Power with Operational Challenges</h3><p>BTCPay Server stands out from the others as a fully <strong>decentralized, self-hosted</strong> crypto payment processor. Rather than relying on a third-party service, merchants (or a hosting partner of their choice) run the BTCPay Server software on their own server, connected to their own Bitcoin (and other crypto) nodes. This model eliminates the intermediary – <strong>there is no central BTCPay company holding funds or routing transactions</strong>. In terms of failure modes, this removes a huge category of risk: a BTCPay setup isn’t affected by external service outages or a provider going out of business. It’s censorship-resistant and continues to operate as long as the underlying blockchains and the merchant’s server are running. Indeed, BTCPay was born as a reaction to BitPay’s perceived shortcomings, with the mantra “<strong>This is lies, you’re obsolete</strong>” directed at centralized processors.</p><p>However, BTCPay Server is not without its own challenges from a resilience perspective. The responsibility for uptime and maintenance shifts entirely onto the merchant (or their IT team). <strong>Operational complexity is the trade-off for sovereignty.</strong> To use BTCPay reliably, one must maintain a Bitcoin full node (and nodes for any other supported cryptocurrencies) in sync, ensure the server hosting BTCPay has high uptime, handle backups, upgrades, and security of the system. Many small merchants may find this daunting. If the BTCPay server goes down or the node falls out of sync (for example, if the server was offline for a time and needs to catch up), the payment system can fail to detect transactions or generate new invoices. Common issues include blockchain sync problems, configuration errors, or resource exhaustion (disk space for the blockchain, etc.). For instance, if a BTCPay server’s Bitcoin node runs in pruned mode and is offline too long, it might miss recognizing certain payments – the BTCPay documentation notes that having the server offline for an extended period can lead to these kinds of issues.</p><p>Support is another area of concern. <strong>There is no official support hotline for BTCPay</strong>, only community forums and documentation. If a merchant encounters a bug or their instance crashes, they must troubleshoot it themselves or seek help from the open-source community. The BTCPay project makes it clear that it’s just software, not a service: <em>“BTCPay Server is an open-source self-hosted stack, not a company… the community has no control over who uses the software or how”</em>. This means <em>each merchant effectively is their own payment provider</em>. While this is empowering, it demands a level of technical ability and preparedness that some businesses might lack. If a sole developer who set up the BTCPay server leaves the company or is unreachable during an outage, the business could be stuck – which is a different kind of continuity risk.</p><p>Additionally, high availability setups for BTCPay require extra effort. Running a <strong>redundant BTCPay cluster</strong> (for failover) is not straightforward out of the box. A merchant would have to engineer a solution with multiple servers and a load balancer, and ensure the underlying wallet (e.g., an xpub key or hot wallet) is shared in a way that doesn’t double-spend or reuse addresses improperly. Few merchants implement this, meaning most BTCPay deployments run on a single server instance. If that server or its network goes down, payments cannot be processed until it’s back online. There is also the question of updates – staying up to date with security patches is vital (since the server deals with money), but updates might introduce changes requiring careful rollout to avoid breaking the integration.</p><p>In summary, BTCPay Server offers freedom from third-party failure modes but introduces <strong>operational complexity as its own vulnerability</strong>. The technical robustness of the software is generally high, and many have successfully processed thousands of payments through BTCPay. Yet, without strong in-house technical support or a trusted hosting partner, merchants could find themselves in over their heads during a crisis. Lack of formal support and the need for self-managed continuity planning are the main negatives from a BCP perspective.</p><p><strong>Negative Lens Summary:</strong> Across BitPay, NOWPayments, and BTCPay Server we see a spectrum: from highly centralized to fully self-hosted. BitPay and similar centralized gateways concentrate risk on their infrastructure and policies – leading to downtime and compliance-related breakages – whereas BTCPay distributes risk to the merchant’s own infrastructure – eliminating some threats but requiring the merchant to handle all contingencies. In between, hybrid models like NOWPayments try to reduce custody risk but still face many of the same support and uptime pitfalls as any service provider. Notably, <strong>none of these solutions inherently provides a seamless failover mechanism or multi-provider continuity out of the box</strong>. That is left for merchants to design, if they recognize the need.</p><h2 id="h-designing-a-disaster-resilient-crypto-payment-architecture" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Designing a Disaster-Resilient Crypto Payment Architecture</h2><p>Given the pitfalls above, what would an “unbreakable” crypto payment system look like? Designing a disaster-resilient crypto payment architecture means maximizing uptime and robustness at every level of the stack – from blockchain connectivity to application logic – while minimizing dependencies on any single component. Here we outline key principles of such an architecture:</p><ul><li><p><strong>Decentralization and Distributed Infrastructure:</strong> Leverage the decentralized nature of blockchain networks rather than re-centralizing transactions through a single server. A resilient design would avoid having all payments funnel through one service or node. Instead, deploy <strong>multiple independent nodes and servers</strong> to handle blockchain interactions. For example, run Bitcoin and Ethereum nodes in multiple geographic regions or cloud providers; if one node or hosting center goes down, others can continue processing transactions. By distributing the infrastructure, the system can withstand localized outages. This takes inspiration from the Internet and blockchain itself – redundancy and decentralization create natural resilience.</p></li><li><p><strong>Redundancy and Failover at Every Critical Point:</strong> Identify all centralized components in the payment flow and provide redundancy or hot backups for each. This includes the payment gateway application layer, database, blockchain nodes, and external services (like exchange rate providers). High-availability techniques from traditional IT are applicable: use load balancers and clustering for the payment application so that if one instance fails, another automatically takes over. Maintain multiple wallet nodes or RPC endpoints; for instance, have a secondary Bitcoin node (or use a fallback public RPC) ready if the primary node becomes unresponsive. Implement health checks that detect failures and switch to backups in real time. The goal is <strong>no single point whose failure stops the entire system</strong>.</p></li><li><p><strong>Multi-Provider and Multi-Path Design:</strong> A truly robust architecture would not rely on a single service provider or even a single blockchain network. Merchants can design their checkout process to support <strong>multiple payment gateways concurrently</strong> – for example, integrate both a self-hosted BTCPay Server and a third-party service (like NowPayments or others) as a fallback. If the primary method fails (e.g., your server is down), the system could automatically present an alternative payment option to the customer (such as redirecting to a secondary invoice link). Additionally, support multi-chain payments: if, say, the Ethereum network is congested and failing to confirm transactions, a resilient system could offer an alternate route like a Layer-2 network (Polygon, Lightning, etc.) or even accept a different cryptocurrency that’s flowing more smoothly. This requires advanced integration logic but guards against failures that are chain-specific or provider-specific. Essentially, <strong>build optionality</strong> – multiple payments rails instead of just one.</p></li><li><p><strong>Self-Hosted plus Cloud Hybrid Approach:</strong> For merchants who have significant volume, combining self-hosted components with cloud services can yield resilience. For example, run a self-hosted BTCPay Server as primary, but also have a lightweight cloud-based processor API as backup for critical moments (or vice versa). The self-hosted component gives control and censorship-resistance, while the cloud service can act as insurance if the merchant’s infrastructure has a problem. Some merchants even keep <strong>manual fallback addresses</strong> or static QR codes ready (for instance, a pre-generated address for accepting a cryptocurrency) that can be displayed to a customer in an emergency if the dynamic system fails. Though not ideal (manual reconciliation would be needed later), it ensures the sale isn’t lost entirely when the tech fails.</p></li><li><p><strong>Robust Wallet and Key Management:</strong> Security and continuity of the wallet layer (where funds ultimately go) must be part of the architecture. Use <strong>multi-signature wallets and distributed key holders</strong> to avoid losing access to funds if one key is compromised or one team member is unreachable. For example, require 2-of-3 keys to move funds, stored in different locations – this way, even in a disaster scenario, authorized signers in another office or a backup can still access the funds. Key backups should be meticulously maintained so that even if infrastructure is destroyed, the crypto assets are not lost (this ties into BCP on the treasury side). Also, design the system such that if an outgoing conversion or transfer fails (say to move crypto to exchange), the funds remain in a secure wallet the merchant controls, not stuck in limbo at a third party.</p></li><li><p><strong>Exchange and Liquidity Redundancy:</strong> Many merchants immediately convert crypto to fiat. A resilient payment setup will integrate with <strong>multiple exchange partners or OTC desks</strong> so that if one exchange API is down or a liquidity provider halts conversions, an alternate path is available. For instance, have accounts with two exchanges and implement automatic failover for settlement: if Exchange A doesn’t respond, switch to Exchange B for converting that BTC to USD. This protects against exchange downtime or suspension (which is not hypothetical – exchanges occasionally pause withdrawals or have maintenance). Maintaining some stablecoin or fiat reserve is also wise, so that temporary disruptions in conversion do not affect merchant cash flow.</p></li><li><p><strong>Monitoring, Alerts, and Incident Response:</strong> An unbreakable system isn’t just about technology, but also about processes. Implement comprehensive monitoring of all components – node health, payment queue backlogs, API latency, etc. – with real-time alerts for anomalies. Prepare runbooks for various failure scenarios (node desync, double-spent transaction, invoice underpayment, etc.) and <strong>practice disaster simulations</strong>. Regularly test failover mechanisms (e.g., deliberately take the primary node offline to ensure the secondary picks up). Staff should be trained on how to manually invoke fallback procedures when needed. The organization’s BCP should specifically address crypto payment continuity: who is responsible for what if the payments stop? How to communicate with customers during an outage? Having multi-channel communication (email, messaging) with any third-party providers is also critical so that during an incident, information flows even if one channel (say the dashboard) is down.</p></li></ul><p>By incorporating the above elements, a crypto payment system can approach “unbreakable” status – resilient against most foreseeable disruptions. The architecture essentially mirrors the redundancy principles of mission-critical traditional systems, but adapted to crypto’s specifics (like blockchain quirks and the need for multi-key management). The core idea is <strong>graceful degradation</strong>: even if one component fails, the system has another path to complete the payment or at least fail safely without losing funds or data.</p><h2 id="h-recommendations-for-merchants-building-continuity-into-crypto-payments" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Recommendations for Merchants: Building Continuity into Crypto Payments</h2><p>For developers, merchants, and product architects looking to implement a fail-safe crypto payment system, here are detailed recommendations distilled from the above analysis:</p><ol><li><p><strong>Choose the Right Architecture and Provider Mix:</strong> Prefer solutions that minimize single points of failure. If you use a third-party payment gateway, ensure it has a strong uptime record and consider running a <strong>parallel self-hosted node or server as a backup</strong>. Conversely, if you go self-hosted, engage a reliable hosted service as a contingency. Don’t rely on any one platform exclusively.</p></li><li><p><strong>Implement High Availability for Self-Hosted Components:</strong> If running your own infrastructure (e.g., BTCPay Server or custom gateway), deploy it in a <strong>high-availability setup</strong>. This means multiple servers in different zones, with a load balancer or failover mechanism. Run multiple blockchain nodes (Bitcoin, Ethereum, etc.) so that one node can take over if another fails. Use managed node cluster services or geographically distributed VPS to increase resilience. Regularly test that if one node is taken down, your system seamlessly connects to the backup.</p></li><li><p><strong>Utilize Multi-Currency and Layer-2 Support:</strong> Expand your payment options to include multiple cryptocurrencies and Lightning/Layer-2 networks. This isn’t just for customer convenience, but for continuity – it gives you flexibility if one network is congested or experiencing issues. For example, if Ethereum fees spike or the network halts (as has happened during outages), you can fall back to accepting USDC on an alternative chain (like Polygon) for the duration. Supporting Bitcoin Lightning as well as on-chain Bitcoin means you can still take small payments even if the blockchain is slow. <strong>Diversify your payment rails</strong> to avoid being crippled by any single network problem.</p></li><li><p><strong>Demand Transparency and Support SLAs from Providers:</strong> When evaluating crypto payment service providers (Coinify, BitPay, NOWPayments, etc.), look beyond features and price. Investigate their <strong>uptime history and support responsiveness</strong>. Ask if they have status pages or post-mortems of incidents. If a provider cannot commit to support response times or doesn’t have a status dashboard, that’s a red flag. Ideally, get a provider that offers a service-level agreement (SLA) or at least documented procedures for outages. Ensure you maintain up-to-date contacts (account managers or support engineers) at the provider that you can reach out to directly in an emergency – don’t rely solely on generic support tickets if your business is on the line.</p></li><li><p><strong>Incorporate Business Continuity Planning for Payments:</strong> Treat your crypto payment system as critical infrastructure and include it in your organization’s BCP drills. Develop a <strong>crypto-specific continuity plan</strong> that covers scenarios like: “What if our payment gateway API is down?”, “What if our on-site crypto server is hacked or crashes?”, “What if a regulatory change overnight prevents our provider from operating?”. For each scenario, plan responses: e.g., having an alternative provider ready to activate, switching to manual invoice processing, or pausing crypto payments and communicating to customers. Also plan for recovery: e.g., if you switch to a backup system, how to later reconcile and consolidate data from the downtime period.</p></li><li><p><strong>Ensure Security Does Not Become a Weak Link:</strong> High availability means little if a security breach takes you down instead. Follow best practices for wallet security (use multi-sig or at least multi-factor protected wallets for merchant funds). Keep private keys <strong>out of any single server</strong> that could be compromised – BTCPay, for example, can be used with xpub (public keys) so the server can’t spend funds even if hacked. Use hardware security modules or hardware wallets for signing if possible. By securing keys and using <strong>multi-signature redundancy</strong>, you also ensure that even in a disaster scenario (one key lost or one signer unavailable), funds are not permanently locked.</p></li><li><p><strong>Maintain Liquidity Buffers and Multiple Off-Ramps:</strong> To handle conversion and payouts, have accounts with multiple exchanges or fiat off-ramps. Keep a buffer of crypto and fiat to cover short-term needs if conversions are delayed. That way, if your primary exchange is down or a bank transfer is slow, your operations can continue for a time using reserves. This is classic BCP for finances – analogous to keeping some generators and fuel in case the power grid fails.</p></li><li><p><strong>Monitor Aggressively and Automate Recovery:</strong> Deploy comprehensive monitoring on all aspects of the crypto payment flow. Set up alerts for anomalies like blockchain backlogs (e.g., if 0 confirmations take unusually long), dropped API requests, or payment timeouts. Use these signals to trigger automated failover where possible. For instance, if your monitoring detects that your primary BTC node hasn’t reported a new block in X minutes (potentially down), have your system automatically switch to a secondary node or a public RPC until the primary is back. Automation can greatly reduce downtime by reacting faster than a human. Similarly, implement automatic retries for transactions and payouts – if one attempt fails due to network issues, try alternative routes without manual intervention.</p></li><li><p><strong>Keep It Simple for the Customer:</strong> Despite all the backend sophistication, aim to keep the checkout experience simple and reliable for the end-user. Provide clear instructions and multiple payment options (for example, show a <strong>QR code by default, but also offer a “connect wallet” button</strong> for those who prefer it, rather than forcing one method). If a payment method is temporarily unavailable, communicate that on the checkout page and present alternatives (e.g., “Ethereum network is currently congested, you may switch to USDC on Polygon or use Bitcoin”). A customer who encounters an error with no explanation is likely gone forever – so design the system to <strong>fail gracefully</strong>, guiding the user to complete the payment via another path if needed.</p></li><li><p><strong>Leverage Community and Open-Source Innovations:</strong> Finally, stay updated on the latest tools and best practices in the crypto payments space. Open-source projects and communities often share solutions for resilience. For example, there are emerging solutions for <strong>multi-node blockchain API clusters</strong> and <strong>payment gateway failover modules</strong>. Engaging with developer communities (such as BTCPay Server’s community or others) can provide insights into how peers are achieving redundancy. As the ecosystem evolves (new Layer-2 networks, better protocols), be ready to adopt improvements that enhance reliability.</p></li></ol><p>By following these recommendations, merchants can significantly reduce the risk of their crypto payment system “failing” in the face of adversity. No system can be 100% failure-proof, but with rigorous design and planning, the impact of failures can be minimized such that crypto payments remain a dependable part of the business even in turbulent conditions.</p><h2 id="h-conclusion" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Conclusion</h2><p>Crypto payment systems present new opportunities for merchants, but they also introduce new failure modes that must be addressed through careful architecture and planning. Many of the high-profile failures – from Coinify’s support collapse to Coinbase Commerce’s usability hurdles and BitPay’s outages – underscore a common lesson: <strong>resilience cannot be an afterthought</strong>. Centralized gateways can fail spectacularly without decentralization and redundancy, while do-it-yourself solutions can falter without operational discipline. The technical depth exists today to build payment systems that are far more robust: by combining decentralized network benefits with redundant infrastructure and solid BCP processes, merchants can achieve near-continuous availability and security in crypto transactions.</p><p>The stakes are high because downtime or lost transactions directly equate to lost revenue and damaged trust. Fintech professionals and product architects should treat crypto payment rails with the same seriousness as any mission-critical payment infrastructure. That means learning from past breakdowns and implementing the protections and fail-safes detailed in this paper. Ultimately, the promise of cryptocurrency in payments – global, fast, and censorship-resistant transactions – can only be realized in practice if the systems built on top are equally resilient and reliable. By acknowledging and engineering around the failure modes, we can move closer to crypto payment solutions that don’t just work in ideal conditions, but <em>endure</em> and <em>recover</em> in the face of real-world challenges, truly earning the label of “unbreakable” payment architecture.</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[Lazarus Group or Geopolitical Bogeyman? Re-examining North Korea’s Alleged Hacks]]></title>
            <link>https://paragraph.com/@defi-in-security/lazarus-group-or-geopolitical-bogeyman-re-examining-north-korea-s-alleged-hacks</link>
            <guid>I1cBsO6dnPBPEv8RXfzL</guid>
            <pubDate>Tue, 01 Apr 2025 18:45:25 GMT</pubDate>
            <description><![CDATA[The Bybit Heist: Largest Crypto Hack Attributed to LazarusOn February 21, 2025, a routine transfer from the cold wallets of Bybit – one of the world’s largest cryptocurrency exchanges – triggered an alarm. Within minutes, an astonishing $1.5 billion in Ethereum had vanished from the exchange’s vaults. The attackers exploited a weakness in Bybit’s multi-signature wallet system, covertly inserting a delegatecall into the transaction approval process to reroute funds into their own addresses (Ho...]]></description>
            <content:encoded><![CDATA[<h2 id="h-the-bybit-heist-largest-crypto-hack-attributed-to-lazarus" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">The Bybit Heist: Largest Crypto Hack Attributed to Lazarus</h2><p>On <strong>February 21, 2025</strong>, a routine transfer from the cold wallets of Bybit – one of the world’s largest cryptocurrency exchanges – triggered an alarm. Within minutes, an astonishing <strong>$1.5 billion in Ethereum</strong> had vanished from the exchange’s vaults. The attackers exploited a weakness in Bybit’s multi-signature wallet system, covertly inserting a <code>delegatecall</code> into the transaction approval process to reroute funds into their own addresses (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://cointelegraph.com/learn/articles/how-the-bybit-hack-happened#:~:text=Once%20inside%20the%20UI%2C%20the,A%20%E2%80%98delegatecall%E2%80%99%20instruction%20was%20secretly">How the Bybit hack happened: inside the $1.5 billion crypto heist</a>). It was an audacious, highly sophisticated breach – now recorded as the <strong>largest cryptocurrency heist in history</strong>.</p><p>In the immediate aftermath, blockchain tracing firms sprang into action. TRM Labs tagged the culprit wallets and soon <strong>confirmed a North Korean nexus</strong>, noting overlaps with addresses from previous state-sponsored crypto heists. Within five days, the FBI publicly <strong>attributed the Bybit hack to Lazarus Group</strong>, the infamous North Korean hacking unit. This attribution aligned with a well-worn pattern: over the past decade, many of the biggest crypto exchange robberies – from <strong>Ronin Bridge (Axie Infinity)</strong> to <strong>KuCoin</strong> – have been pinned on Lazarus. U.S. authorities and private analysts alike are convinced that Pyongyang’s cyber operatives are behind an ongoing digital crime spree that has netted <strong>over $5–6 billion in crypto since 2017</strong> (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.elliptic.co/blog/bybit-hack-largest-in-history#:~:text=Elliptic%20has%20attributed%20the%20Bybit,reportedly%20spent%20on%20the%20country%E2%80%99s">The largest theft in history - following the money trail from the Bybit Hack</a>) (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.trmlabs.com/resources/blog/the-bybit-hack-following-north-koreas-largest-exploit#:~:text=To%20put%20the%20magnitude%20of,impact%20operations">The Bybit Hack: Following North Korea’s Largest Exploit | TRM Insights</a>). But as the Bybit case grabs headlines, a critical question resurfaces: <strong>Are these attributions rock-solid, or has “Lazarus” become a convenient scapegoat for the crypto world’s failures?</strong></p><h2 id="h-a-string-of-crypto-exchange-breaches" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">A String of Crypto Exchange Breaches</h2><p>The Bybit exploit is only the latest in a long series of crypto exchange and DeFi hacks attributed to <strong>“Lazarus Group,”</strong> a shadowy hacking collective allegedly run by North Korea’s Reconnaissance General Bureau (RGB). Since the mid-2010s, this group (also tracked as <strong>APT38</strong> for its financial crimes unit) has been linked to an escalating campaign of digital theft targeting global financial platforms. Consider some of the <strong>notable heists</strong>:</p><ul><li><p><strong>Bangladesh Bank, 2016:</strong> An $81 million theft via fraudulent SWIFT transfers from a Bangladesh central bank account – part of an attempted $1 billion caper – was <strong>“widely attributed”</strong> to Lazarus (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.c4isrnet.com/home/2017/06/02/new-report-details-clear-attribution-of-lazarus-group-hacks-to-north-korean-military/#:~:text=Group,widely%20attributed%20to%20Lazarus%20Group">New report details &apos;clear attribution&apos; of Lazarus Group hacks to North Korean military</a>). U.S. officials later stated that Pyongyang was likely behind this unprecedented bank hack (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.group-ib.com/blog/lazarus/#:~:text=in%20the%20bank%E2%80%99s%20security%20to,on%20the%20Bangladeshi%20Central%20Bank">LAZARUS ARISEN | Group-IB Blog</a>).</p></li><li><p><strong>Youbit (Yapizon) Exchange, 2017:</strong> A South Korean crypto exchange suffered back-to-back hacks (17% of assets in April 2017, and another in December) forcing it into bankruptcy. South Korean intelligence pointed the finger at North Korean actors, presumed to be Lazarus, for these attacks – an early sign that Pyongyang’s hackers were pivoting to cryptocurrency.</p></li><li><p><strong>Coincheck, 2018:</strong> In one of the largest exchange thefts ever, <strong>$530 million</strong> in NEM tokens were stolen from Japan’s Coincheck. While never officially solved, many experts suspected Lazarus given the scale and the target (Japan has been in Lazarus’s crosshairs before). The incident exposed poor security (tokens stored in a single hot wallet) yet discussions often focused more on <strong>whodunit</strong> than on Coincheck’s lapses.</p></li><li><p><strong>Upbit, 2019:</strong> In November 2019, hackers drained <strong>342,000 ETH</strong> (then ~$50 million) from South Korea’s Upbit exchange. It took five years, but in 2024 <strong>South Korea’s National Police</strong> conclusively <strong>blamed the Upbit hack on Lazarus and a sibling group called Andariel</strong>, citing traced crypto flows, North Korean IP addresses, and even the use of <strong>North Korean language</strong> in the attack infrastructure. Investigators revealed the thieves laundered the ETH through dozens of brokers – selling roughly 57% on shady exchanges allegedly run by North Koreans – before dispersing the rest through 51 overseas platforms. This marked the first official confirmation by Seoul that the <strong>Upbit heist was a DPRK operation</strong> (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://cointelegraph.com/news/upbit-hack-lazarus-south-korea-police#:~:text=North%20Korean%20police%20confirm%20hack,perpetrators%20after%20five%20years">South Korea confirms North Korea behind $50M Upbit hack</a>).</p></li><li><p><strong>KuCoin, 2020:</strong> In September 2020, <strong>$275 million</strong> in crypto was stolen from Singapore-based KuCoin’s hot wallets. Blockchain forensics by Chainalysis later identified <strong>Lazarus Group as the culprit</strong>, noting the thieves’ telltale laundering method: slicing funds into uniform chunks and feeding them into mixers in a systematic, “assembly-line” fashion. The <strong>hackers had obtained KuCoin’s private keys</strong> – likely via social engineering or malware – and, after the theft, laundered the coins through mixers and DeFi swaps. Investigators observed that the KuCoin hackers <em>re-used a laundering pattern Lazarus employed in past heists</em>, strengthening the attribution. (Notably, KuCoin’s CEO managed to recover a large portion of funds, but Lazarus still walked away with tens of millions (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.chainalysis.com/blog/lazarus-group-kucoin-exchange-hack/#:~:text=theft%20of%20the%20year%2C%20and,worth%20of%20the%20stolen%20funds">Lazarus Group Pulled Off 2020’s Biggest Exchange Hack and Appears to be Exploring New Money Laundering Options - Chainalysis</a>).)</p></li><li><p><strong>Ronin Bridge (Axie Infinity), 2022:</strong> In March 2022, attackers <strong>exploited the Ronin sidechain bridge</strong> used by Axie Infinity, absconding with <strong>$625 million</strong> (173,600 ETH and millions in USDC). U.S. Treasury and the FBI swiftly <strong>identified the Ethereum address</strong> holding the loot as controlled by Lazarus, and sanctioned the wallet within weeks (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://techcrunch.com/2022/04/15/us-officials-link-north-korean-lazarus-hackers-to-625m-axie-infinity-crypto-theft/#:~:text=The%20Treasury%20Department%E2%80%99s%20Office%20of,DeFi%20scams%2C%20hacks%20and%20exploits">N Korean Lazarus hackers tied to $625M theft</a>). Blockchain analytics confirmed that the same address had been used in the hack, providing a direct link to the North Korean crew. This remains one of the largest DeFi hacks on record. Subsequent reporting uncovered that Lazarus operatives had <strong>social-engineered an Axie developer via LinkedIn</strong>, sending a poisoned job offer PDF that helped them penetrate the network – a textbook Lazarus tactic.</p></li><li><p><strong>Horizon Bridge (Harmony), 2022:</strong> Another cross-chain bridge attack in June 2022 saw ~$100 million stolen. In January 2023, the <strong>FBI officially attributed the Horizon Bridge theft to Lazarus (APT38)</strong> (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.fbi.gov/news/press-releases/fbi-confirms-lazarus-group-cyber-actors-responsible-for-harmonys-horizon-bridge-currency-theft#:~:text=North%20Korean%20malicious%20cyber%20actor,reported%20on%20June%2024%2C%202022">FBI Confirms Lazarus Group Cyber Actors Responsible for Harmony&apos;s Horizon Bridge Currency Theft — FBI</a>). The Bureau even published a list of blockchain wallet addresses linked to the hack, underlining how diligently they were tracking Lazarus’s crypto haul. By then, analysts noted Lazarus had begun using <strong>privacy mixers (like Tornado Cash, Wasabi) and chain hopping</strong> to obscure their tracks – tactics observed again in the Bybit case.</p></li><li><p><strong>Recent 2023 Targets:</strong> The crypto boom and bust of 2021–2022 gave Lazarus ample new targets. In <strong>2023, the FBI pinned a $100 million hack of Atomic Wallet</strong> (a non-custodial wallet service) on North Korean actors. The <strong>crypto casino </strong><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="http://Stake.com"><strong>Stake.com</strong></a><strong> lost ~$41 million</strong> to Lazarus-linked hackers in September 2023 (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.trmlabs.com/resources/blog/the-bybit-hack-following-north-koreas-largest-exploit#:~:text=match%20at%20L237%20,Binance%20Smart%20Chain%2C%20and%20Polygon">The Bybit Hack: Following North Korea’s Largest Exploit | TRM Insights</a>). And multiple <strong>DeFi platform attacks</strong> were suspected to be the work of Lazarus or copycats, as the group showed growing prowess in exploiting smart contract vulnerabilities in addition to traditional phishing.</p></li></ul><p>By early 2025, North Korea’s crypto hacking tally is staggering. Elliptic, a blockchain analytics firm, estimates <strong>over $6 billion in cryptocurrency has been stolen by North Korea-linked hackers since 2017</strong>. U.N. sanctions monitors reported that <strong>2022 was a record-breaking year</strong> with at least <strong>$630 million (and possibly over $1 billion) in crypto assets stolen by DPRK groups</strong> (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.reuters.com/technology/record-breaking-2022-north-korea-crypto-theft-un-report-2023-02-06/#:~:text=,member%20states%20and%20cybersecurity%20firms">Exclusive: Record-breaking 2022 for North Korea crypto theft, UN report says | Reuters</a>). These funds are believed to bankroll Pyongyang’s sanctioned nuclear and missile programs – perhaps covering as much as <strong>half of the regime’s missile development budget</strong> according to some claims (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://dev.to/scofieldidehen/the-lazarus-hackers-everything-you-know-is-a-lie-l05#:~:text=The%20United%20nations%20claims%20Lazarus,have%20the%20talent%20or%20tech">The Lazarus Hackers: Everything You Know Is a Lie - DEV Community</a>). Small wonder that law enforcement and intelligence agencies worldwide sound the alarm: by their account, <strong>Lazarus Group has become the most prolific cryptocurrency bandit in history</strong>, and a uniquely dangerous fusion of state espionage and organized crime (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.elliptic.co/blog/bybit-hack-largest-in-history#:~:text=North%20Korea%20is%20the%20most,the%20clock%20with%20Bybit%2C%20our">The largest theft in history - following the money trail from the Bybit Hack</a>).</p><p>Yet amid the headlines and government press releases, a troubling pattern emerges. With each new hack promptly blamed on this <strong>same elusive cabal</strong>, one might ask: <strong>Has “Lazarus” become a catch-all villain, a default culprit whenever crypto vanishes into the ether?</strong> Are these attributions always backed by solid evidence, or has Lazarus evolved into a convenient foil for deeper industry problems?</p><h2 id="h-inside-the-lazarus-playbook-malware-phishing-and-blockchain-trails" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Inside the Lazarus Playbook: Malware, Phishing, and Blockchain Trails</h2><p>To evaluate the reliability of attribution, one must understand how investigators link these hacks to Lazarus in the first place. <strong>What evidence is used to pin a theft on a North Korean state-backed hacker, rather than, say, a rogue cybercriminal in Eastern Europe?</strong> The answer lies in a mix of <strong>technical forensics, behavioral analysis, and sometimes geopolitical context.</strong></p><p><strong>Malware and Infrastructure:</strong> A classic clue is the reuse of malicious code or tools previously tied to Lazarus. For instance, the malware that breached Sony Pictures in 2014 (Lazarus’s infamous retaliation for <em>The Interview</em> film) shared code with viruses later used to infiltrate banks (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://dev.to/scofieldidehen/the-lazarus-hackers-everything-you-know-is-a-lie-l05#:~:text=November%202014%2C%20Sony%20Pictures%20Entertainment,code%20similarities%20to%20earlier%20attacks">The Lazarus Hackers: Everything You Know Is a Lie - DEV Community</a>). Cybersecurity firms like Novetta and Kaspersky noted unique snippets and encryption routines that appeared in multiple Lazarus-attributed operations, suggesting a common toolkit. However, <strong>savvy hackers can plant false flags by intentionally using someone else’s code</strong>. In fact, Lazarus itself has done this: after 2016, <strong>they started inserting Russian-language strings and using Russian-developed packers (like Enigma Protector) in their malware to confuse analysts</strong>. Such ploys did mislead some researchers into initially suspecting Russian actors (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.c4isrnet.com/home/2017/06/02/new-report-details-clear-attribution-of-lazarus-group-hacks-to-north-korean-military/#:~:text=investigators%20included%20the%20use%20of,speaking%20hackers">New report details &apos;clear attribution&apos; of Lazarus Group hacks to North Korean military</a>). This works in reverse as well – theoretically, a non-Korean attacker could sprinkle Korean code or mimic Lazarus tools to point the finger at Pyongyang. Recognizing this, serious investigators <strong>no longer rely on code similarity alone</strong>. As Group-IB cautioned in its landmark <em>Lazarus Arisen</em> report, <strong>malware reuse is common and “does not provide conclusive evidence of attribution” without other context (</strong><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.group-ib.com/blog/lazarus/#:~:text=In%20February%202017%2C%20several%20Polish,banks%20were%20compromised"><strong>LAZARUS ARISEN | Group-IB Blog</strong></a><strong>)</strong>.</p><p>Thus, analysts dig deeper into <strong>infrastructure</strong>. Group-IB’s researchers painstakingly mapped Lazarus’s command-and-control (<strong>C2</strong>) servers across a three-tiered botnet architecture. By following the digital bread crumbs (malware beacons, SSL certificates, VPN usage), they traced multiple attacks back to a pair of <strong>IP addresses in Pyongyang’s Potonggang district</strong> – home to North Korea’s military intelligence bureau. One of those IPs (175.45.178.222) fell in the same subnet range as addresses known to be used by <strong>Bureau 121</strong> (the clandestine RGB unit overseeing cyber-ops). This kind of network telemetry – essentially catching the hackers connecting from home base – is about as strong as technical attribution gets. It led Group-IB to conclude with “clear attribution” that Lazarus is run directly by the North Korean state (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.c4isrnet.com/home/2017/06/02/new-report-details-clear-attribution-of-lazarus-group-hacks-to-north-korean-military/#:~:text=A%20report%20published%20this%20week,cyberattacks%20and%20espionage%20against%20enemies">New report details &apos;clear attribution&apos; of Lazarus Group hacks to North Korean military</a>) (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.group-ib.com/blog/lazarus/#:~:text=Group,they%20have%20planned%20to%20attack">LAZARUS ARISEN | Group-IB Blog</a>). Similarly, South Korean investigators in the Upbit case cited <strong>North Korean IP login traces and language indicators</strong> as proof of DPRK involvement (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://cointelegraph.com/news/upbit-hack-lazarus-south-korea-police#:~:text=involvement%20in%20a%20cryptocurrency%20hack">South Korea confirms North Korea behind $50M Upbit hack</a>).</p><p>Another Lazarus hallmark is their <strong>modus operandi</strong> in breaching targets. Over time, certain <strong>tactics, techniques, and procedures (TTPs)</strong> have recurred:</p><ul><li><p><strong>Spear Phishing and Social Engineering:</strong> Lazarus hackers are masters of the long con. They commonly pose as recruiters on LinkedIn or other social networks, targeting employees of crypto firms or banks with enticing job offers. The U.N. recently warned that North Korean operatives initiate contacts on LinkedIn, build trust, then shift to WhatsApp or email to deliver malware-laced documents (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.reuters.com/technology/record-breaking-2022-north-korea-crypto-theft-un-report-2023-02-06/#:~:text=The%20sanctions%20monitors%20said%20the,in%20organizations%20across%20various%20countries">Exclusive: Record-breaking 2022 for North Korea crypto theft, UN report says | Reuters</a>). In one 2022 campaign, Lazarus sent out bogus job offer documents (e.g. “Engineering Position at CryptoCompany.pdf”) that, when opened, executed spyware on the recipient’s computer (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.malwarebytes.com/blog/news/2022/12/lazarus-group-uses-fake-cryptocurrency-apps-to-plant-applejeus-malware#:~:text=profile%20attacks">Lazarus group uses fake cryptocurrency apps to plant AppleJeus malware</a>). The <strong>Axie Infinity/Ronin hack</strong> followed this playbook to a tee: an engineer was duped by a fake job offer, giving Lazarus the foothold to compromise private keys. Phishing for exchange credentials or tricking staff into installing backdoors remains a go-to move for Lazarus, who often prefer <strong>stolen login credentials over laborious zero-day exploits</strong> (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.c4isrnet.com/home/2017/06/02/new-report-details-clear-attribution-of-lazarus-group-hacks-to-north-korean-military/#:~:text=Lazarus%20Group%20,day%20exploits">New report details &apos;clear attribution&apos; of Lazarus Group hacks to North Korean military</a>).</p></li><li><p><strong>Trojanized Crypto Apps – Operation AppleJeus:</strong> Perhaps the most insidious Lazarus tactic is creating <strong>fake cryptocurrency applications and websites</strong> to infect victims. Since <strong>2018</strong>, Lazarus (specifically its sub-group sometimes dubbed BlueNoroff/APT38) has run <strong>“Operation AppleJeus.”</strong> They build spoofed crypto trading platforms or wallets and circulate them to lure investors and exchange employees. The apps function normally but install a backdoor called <strong>AppleJeus</strong>. Through this, Lazarus can eventually <strong>steal the private keys</strong> and credentials needed to empty victims’ crypto accounts. They have masqueraded as everything from trading bots to ICO platforms – one recent fake site <strong>cloned a legitimate crypto trading firm (HaasOnline) and offered a trojanized app called “BloxHolder,” which delivered AppleJeus malware bundled with real trading software (</strong><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.malwarebytes.com/blog/news/2022/12/lazarus-group-uses-fake-cryptocurrency-apps-to-plant-applejeus-malware#:~:text=The%20campaign%20started%20when%20Lazarus,create%20complex%20automated%20trading%20algorithms"><strong>Lazarus group uses fake cryptocurrency apps to plant AppleJeus malware</strong></a><strong>)</strong>. This blend of social engineering and malware is deadly: it gets Lazarus inside networks undetected, from where they can pivot to the crown jewels – cold wallet keys, exchange backend servers, or treasury smart contracts.</p></li><li><p><strong>Exploiting Trust and Process Weaknesses:</strong> The Bybit hack underscores Lazarus’s ability to target not just software vulnerabilities but <strong>operational vulnerabilities</strong>. Bybit’s security relied on a multi-sig cold wallet requiring several approvals for large transfers (an industry best practice). Yet the attackers found a weakness in how those transactions were generated or displayed. <strong>They penetrated the exchange’s internal systems (possibly via an insider or phishing) and manipulated the transaction data shown to the signers</strong> (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://cointelegraph.com/learn/articles/how-the-bybit-hack-happened#:~:text=Once%20inside%20the%20UI%2C%20the,A%20%E2%80%98delegatecall%E2%80%99%20instruction%20was%20secretly">How the Bybit hack happened: inside the $1.5 billion crypto heist</a>). In doing so, they inserted a hidden call that changed the destination of the funds. The signers – seeing what looked like a routine transfer – unwittingly co-signed the theft. This was a <strong>supply chain attack on the transaction pipeline</strong> itself, showing Lazarus’s adaptability. Likewise, Lazarus has exploited software supply chains (for example, corrupting updates for legitimate apps) and API vulnerabilities in DeFi protocols when direct phishing isn’t enough. <strong>Their repertoire spans from old-school tactics (USB malware, DDoS as distraction) to cutting-edge DeFi hacks</strong>, whichever best suits the target at hand (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.group-ib.com/blog/lazarus/#:~:text=Lazarus%20is%20known%20to%20have,conduct%20money%20thefts%20and%20espionage">LAZARUS ARISEN | Group-IB Blog</a>) (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://cointelegraph.com/learn/articles/how-the-bybit-hack-happened#:~:text=The%20February%202025%20Bybit%20hack,contract%20logic%20and%20offchain%20infrastructure">How the Bybit hack happened: inside the $1.5 billion crypto heist</a>).</p></li><li><p><strong>Cash-Out and Laundering Patterns:</strong> One reason investigators swiftly cry “Lazarus” after a crypto theft is the thieves’ subsequent behavior on the blockchain. <strong>North Korea’s laundering operations have a distinct fingerprint.</strong> They often <strong>swap stolen tokens for ETH or BTC immediately</strong> – because unlike many altcoins, those cannot be frozen by any central issuer. Next, they <strong>fragment the funds into hundreds of new addresses</strong> (e.g. splitting Ether into chunks of just under 100 ETH each) and begin a marathon series of hops. In the KuCoin case, Chainalysis observed dozens of equal-sized Bitcoin payments fed into mixers one after another – a method <strong>Lazarus used repeatedly to launder funds while minimizing traceable patterns</strong> (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.chainalysis.com/blog/lazarus-group-kucoin-exchange-hack/#:~:text=We%20were%20able%20to%20attribute,The%20KuCoin">Lazarus Group Pulled Off 2020’s Biggest Exchange Hack and Appears to be Exploring New Money Laundering Options - Chainalysis</a>). After mixing, the coins emerge into wallets that then often funnel into <strong>Asia-based over-the-counter (OTC) brokers or low-regulation exchanges</strong>, where they can be converted to fiat. In the Upbit hack, for instance, police found more than half of the stolen Ether was cashed out via exchanges allegedly controlled by North Korean operators (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://cointelegraph.com/news/upbit-hack-lazarus-south-korea-police#:~:text=information%20from%20the%20United%20States,Federal%20Bureau%20of%20Investigation">South Korea confirms North Korea behind $50M Upbit hack</a>). With DeFi’s rise, Lazarus also began using decentralized exchanges to swap assets across chains, and cross-chain bridges to move value into Bitcoin or other coins where they then employ mixers (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.chainalysis.com/blog/lazarus-group-kucoin-exchange-hack/#:~:text=may%20have%20carried%20out%20that,However%2C%20this%20is%20still%20unconfirmed">Lazarus Group Pulled Off 2020’s Biggest Exchange Hack and Appears to be Exploring New Money Laundering Options - Chainalysis</a>). In almost every recent case – Ronin, Horizon, Atomic Wallet, Stake – <strong>the stolen crypto quickly moves to mixing services or privacy wallets</strong> (Wasabi, Sinbad, Blender, Tornado Cash) known to be favorites of DPRK hackers (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.elliptic.co/blog/bybit-hack-largest-in-history#:~:text=match%20at%20L642%20services,through%20Cryptomixer%20and%20Wasabi%20Wallet">The largest theft in history - following the money trail from the Bybit Hack</a>). This consistency in laundering technique is a smoking gun. In Bybit’s hack, within 48 hours over $160 million was laundered through such channels, “<strong>overwhelming analysts with rapid, high-frequency transactions across multiple platforms</strong>” in what one expert called a “flood-the-zone” approach. Such behavior strongly correlates with past North Korean operations and thus heavily informs attribution decisions.</p></li></ul><p>Taken together, these technical and behavioral clues form a <strong>Lazarus playbook</strong> against which new attacks are compared. In the Bybit case, virtually every element matched: a breach of a high-value exchange via creative vulnerability exploitation, immediate token-swapping and aggressive laundering, and funds ultimately moving to mixer clusters that <strong>only North Korea has been observed using at this scale</strong>. It is little surprise that multiple crypto-tracing companies independently pointed to Lazarus within days, and the FBI felt confident enough to formally accuse North Korea shortly thereafter (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.trmlabs.com/resources/blog/the-bybit-hack-following-north-koreas-largest-exploit#:~:text=Through%20blockchain%20intelligence%2C%20TRM%20Labs,the%20heist%20to%20North%20Korea">The Bybit Hack: Following North Korea’s Largest Exploit | TRM Insights</a>) (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.elliptic.co/blog/bybit-hack-largest-in-history#:~:text=Elliptic%20has%20attributed%20the%20Bybit,reportedly%20spent%20on%20the%20country%E2%80%99s">The largest theft in history - following the money trail from the Bybit Hack</a>).</p><h2 id="h-the-attribution-game-how-solid-is-the-evidence" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">The Attribution Game: How Solid is the Evidence?</h2><p>While the technical evidence tying Lazarus to these hacks is compelling, it is <strong>not infallible</strong>. Attribution in cyberspace is famously tricky – akin to assembling a puzzle with many missing pieces. <strong>Forensic clues can be misinterpreted or manipulated.</strong> And once a narrative takes hold, there’s a risk of confirmation bias reinforcing it. In the case of Lazarus and crypto hacks, a few issues deserve scrutiny:</p><p><strong>1. Copycats and Shared Tools:</strong> As noted, Lazarus doesn’t own a monopoly on crypto hacking techniques. Other criminal groups also use phishing, malware, and mixers. For example, the <strong>“Harvest Finance” DeFi hack of 2020</strong> initially baffled analysts, until Chainalysis noticed that some of the stolen tokens ended up in deposit addresses previously used by Lazarus. This led to <strong>speculation Lazarus was behind Harvest Finance too</strong>, though it was never confirmed (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.chainalysis.com/blog/lazarus-group-kucoin-exchange-hack/#:~:text=confirmed%20by%20the%20mixer%20before,However%2C%20this%20is%20still%20unconfirmed">Lazarus Group Pulled Off 2020’s Biggest Exchange Hack and Appears to be Exploring New Money Laundering Options - Chainalysis</a>). It’s possible Lazarus did it – or just as possible that the real perpetrators knowingly sent a slice of their haul through a Lazarus-linked address to muddy the waters, or that an OTC broker pooled funds from multiple hackers. In other words, <strong>blockchain breadcrumbs can intermix</strong>, and not every appearance of a known Lazarus wallet means Lazarus <em>itself</em> is behind a given crime. The risk is that investigators “seeing what they expect to see” might jump to naming Lazarus prematurely whenever a familiar pattern emerges.</p><p><strong>2. False Flags and Deception:</strong> We’ve seen how Lazarus tried to pose as Russian hackers in 2016 (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.c4isrnet.com/home/2017/06/02/new-report-details-clear-attribution-of-lazarus-group-hacks-to-north-korean-military/#:~:text=About%20the%20same%20time%2C%20also,speaking%20hackers">New report details &apos;clear attribution&apos; of Lazarus Group hacks to North Korean military</a>). Conversely, could others pose as Lazarus? Theoretically yes – by emulating known Lazarus TTPs. For instance, a non-North Korean hacker could deliberately launder funds in the “classic Lazarus” style, use VPS infrastructure in Asia, or reuse malware snippets from public Lazarus samples. Sophisticated attackers might even compromise a server that Lazarus once used and route an operation through it to trigger an attribution to North Korea. It would require considerable effort (and knowledge of Lazarus’s methods), but it’s not impossible. This is why top cyber forensics teams use multiple independent indicators before attributing. In the Bangladesh Bank heist, <strong>some experts initially hesitated to blame North Korea</strong> because the scheme also involved Filipino casinos and Chinese middlemen – it looked at first like a generic transnational crime operation. Only when <strong>similar malware popped up at other banks and an IP address linked to Pyongyang surfaced</strong> did consensus gravitate to Lazarus (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://dev.to/scofieldidehen/the-lazarus-hackers-everything-you-know-is-a-lie-l05#:~:text=February%202016%2C%20hackers%20breached%20Bangladesh%E2%80%99s,to%20Lazarus%2C%20but%20inconsistencies%20lingered">The Lazarus Hackers: Everything You Know Is a Lie - DEV Community</a>) (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.group-ib.com/blog/lazarus/#:~:text=Group,they%20have%20planned%20to%20attack">LAZARUS ARISEN | Group-IB Blog</a>). <strong>Attribution is a mosaic</strong> – one piece of evidence (a fragment of code, an IP, a wallet address) can be a red herring on its own. Patterns over multiple incidents, and preferably a smoking gun like a North Korean IP or state-owned server, are needed for high confidence. In many crypto hacks, such definitive proof can be elusive, coming only much later (if at all). The Upbit case took years of investigation and international cooperation to firmly attribute. That suggests early attributions might sometimes lean on educated guesswork plus the reputation Lazarus has built.</p><p><strong>3. The Lazarus Umbrella:</strong> “Lazarus Group” itself is an umbrella term that lumps together several sub-teams of North Korean hackers. Different cybersecurity vendors use various names – <strong>Bluenoroff</strong> (for the bank-heist specialists), <strong>Andariel</strong> (often focused on South Korea), <strong>Kimsuky</strong> (espionage against think-tanks), etc., all sometimes placed under the Lazarus/Hidden Cobra label. This taxonomy can lead to attribution muddles. For instance, South Korea attributed the Upbit hack to Lazarus <em>and</em> Andariel (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://cointelegraph.com/news/upbit-hack-lazarus-south-korea-police#:~:text=South%20Korean%20authorities%20confirmed%20that,Upbit%20cryptocurrency%20hack%20in%202019">South Korea confirms North Korea behind $50M Upbit hack</a>) – implying a collaboration, or perhaps simply that two units of RGB both took part. When the FBI says “Lazarus did X,” they often mean the North Korean state broadly (they even add “also known as APT38” in statements (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.fbi.gov/news/press-releases/fbi-confirms-lazarus-group-cyber-actors-responsible-for-harmonys-horizon-bridge-currency-theft#:~:text=As%20a%20follow,reported%20on%20June%2024%2C%202022">FBI Confirms Lazarus Group Cyber Actors Responsible for Harmony&apos;s Horizon Bridge Currency Theft — FBI</a>)). The distinction matters because these sub-groups may have different techniques or even different <em>motivations</em>. Some focus purely on theft, others also engage in sabotage or espionage. If a crypto hack’s style doesn’t perfectly match known Lazarus heists, it might still be a <em>different DPRK crew</em>. But public discourse tends to use <strong>“Lazarus” as a catch-all shorthand</strong>, which can gloss over uncertainty. It also means <strong>any mistake by one vendor in labeling an attack can cascade</strong> – if one analyst mis-identifies a criminal gang’s work as Lazarus, others may propagate the claim under the broad Lazarus narrative. In short, <strong>attribution can be over-simplified for the sake of a clear story</strong>.</p><p>Despite these caveats, it’s important to stress: the accumulated evidence for Lazarus Group’s role in many major crypto hacks is substantial and multi-sourced. <strong>No other country or group has been tied to as many high-value crypto thefts</strong>. U.S. prosecutors have even unmasked <strong>individual North Korean operators by name</strong> in indictments, describing their roles in specific bank and crypto attacks. (For example, Park Jin Hyok was indicted for the Sony hack and Bangladesh Bank heist, and in 2021 three other North Korean spies were charged in a sweeping $1.3 billion cyber theft conspiracy (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.justice.gov/archives/opa/pr/three-north-korean-military-hackers-indicted-wide-ranging-scheme-commit-cyberattacks-and#:~:text=A%20federal%20indictment%20unsealed%20today,fraudulently%20market%20a%20blockchain%20platform"> Office of Public Affairs | Three North Korean Military Hackers Indicted in Wide-Ranging Scheme to Commit Cyberattacks and Financial Crimes Across the Globe | United States Department of Justice</a>).) These legal actions indicate a high degree of confidence based on classified intelligence beyond what is publicly released. And yet – <strong>none of those operatives have been arrested</strong>; they remain in North Korea. This leads to a final concern:</p><p><strong>4. Lack of Direct Accountability:</strong> Because we are dealing with nation-state actors shielded by their government, <strong>attributions to Lazarus remain untested in court</strong>. They are allegations backed by forensic and intel evidence, but we rarely see hard proof beyond what private firms report or what agencies selectively disclose. It’s an article of faith that the U.S. wouldn’t sanction individuals or indict them if it wasn’t sure, and so far that faith hasn’t been dramatically contradicted. But skeptics note that without a defendant in the dock, the evidence is never fully aired. <strong>“No Lazarus hacker has ever been caught. All attributions rely on patterns in code and behavior – patterns that could be faked,”</strong> as one critical analysis pointed out (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://dev.to/scofieldidehen/the-lazarus-hackers-everything-you-know-is-a-lie-l05#:~:text=control%20narratives%2C%20and%20manipulate%20public,opinion">The Lazarus Hackers: Everything You Know Is a Lie - DEV Community</a>). This isn’t to say the attributions are wrong, only that they are inherently one-sided. It’s a cat-and-mouse intelligence game where the cat cannot fully reveal its hand (to avoid tipping off the mouse), and the mouse will never confirm its identity (North Korea routinely denies all hacking allegations). The result is the public must trust the investigative process without seeing it fully validated. And trust, as always, should be paired with healthy skepticism.</p><h2 id="h-lazarus-legitimate-menace-or-convenient-scapegoat" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Lazarus: Legitimate Menace or Convenient Scapegoat?</h2><p>The Lazarus Group occupies a unique place in the cybercrime ecosystem – a <strong>state-sponsored syndicate</strong> stealing hundreds of millions in open pursuit of illicit profit. There is little doubt that such a group exists and is actively operating; the <strong>sheer volume of heists</strong>, the <strong>trails of evidence</strong>, and the <strong>consistency with North Korea’s financial needs</strong> make it a credible reality. But the <em>idea</em> of Lazarus has perhaps grown larger than the evidence at times, morphing into something of a <strong>geopolitical bogeyman</strong>.</p><p>Some observers question whether <strong>“Lazarus” has become a go-to boogeyman invoked to explain any major crypto hack</strong>, possibly at the expense of deeper investigation. “Is the Lazarus group the villain, or a phantom – a convenient scapegoat for governments and corporations to mask incompetence or advance hidden agendas?” one commentator mused pointedly. It’s a provocative question. After all, blaming an external <strong>nation-state APT</strong> for a breach can be very <strong>“useful” for those involved:</strong></p><ul><li><p><strong>For Exchange Operators:</strong> Labeling an incident as a state-sponsored attack by an elite group can deflect blame. If North Korea’s best thieves targeted your platform and succeeded, well, <em>“even the strongest vault might fall”</em>. It shifts the narrative from your security failures to the adversary’s prowess. There is a kernel of truth – Lazarus is indeed resourceful – but this framing can excuse poor practices. For instance, if an exchange was keeping keys in an insufficiently secure manner, that fact might get less scrutiny in the rush to vilify Lazarus. After the Coincheck hack, Japanese regulators pressed exchanges to improve cold storage and segregation of assets, but Coincheck’s management largely escaped with light penalties, publicly chalking up the loss to external hackers. <strong>Pointing to Lazarus can sometimes preclude a hard look at whether the victim had proper safeguards.</strong></p></li><li><p><strong>For Governments and Law Enforcement:</strong> Attributing crimes to North Korea can serve political and practical goals. It emphasizes the <strong>need for strong national cyber defenses and sanctions</strong>, thereby justifying budgets and aggressive policies. One theory even posits that Western intelligence hyped the Lazarus threat as a foil after the Snowden leaks damaged their image – by casting themselves as protectors against a rogue state cyber menace, they regain public support. That might be a stretch, but it’s undeniable that <strong>“North Korean hackers” make for a clear villain in narratives</strong>. There’s scant political downside in blaming Pyongyang – unlike attributing a hack to, say, a Chinese group, which could carry diplomatic ramifications, or to a domestic failure, which could embarrass officials. In some cases, loudly naming and shaming North Korea also helps rally international cooperation (as seen in the U.N. reports and sanctions). It’s easier to unite against a common, reviled enemy. However, this can lead to <strong>over-attribution</strong> – seeing North Korean hands in cyber incidents where they might not actually exist.</p></li><li><p><strong>For Cybersecurity Vendors:</strong> The security industry, too, has something to gain. <strong>Fear drives demand for security products and services</strong>. High-profile threat groups like Lazarus are often featured in marketing materials for threat intelligence feeds, anti-APT firewalls, blockchain tracing tools, and so on. As one analyst cynically put it, <em>“Companies have built empires selling ‘Lazarus protection’ – firewalls, threat detectors, and blockchain audits designed to keep the boogeyman at bay.”</em> This isn’t to say those products are snake-oil, but there is an inherent incentive to perhaps amplify how scary and ubiquitous the threat appears. If every major breach is attributed to an unstoppable state hacker unit, companies are more likely to invest in expensive defensive measures. A degree of FUD (fear, uncertainty, doubt) can slip into the discourse, painting Lazarus as almost superhuman. In reality, Lazarus hackers have made mistakes, been foiled, or had near-misses (e.g. a typo “fandation” in a SWIFT transfer stopped them from stealing $900 million more from Bangladesh Bank). They are human and fallible, not all-powerful. But the “mythos” around them can sometimes obscure that, fed by dramatic media portrayals like the BBC’s <em>The Lazarus Heist</em>.</p></li></ul><p>Given these factors, some critics argue that <strong>Lazarus has taken on a mythological aura</strong>. In a provocative piece on <em>Dev</em> community, writer Scofield Idehen asks, <em>“What if the group is a complete fabrication – a cyber-bogeyman conjured by governments and corporations to justify surveillance, control narratives, and manipulate public opinion?”</em> He notes how <strong>no Lazarus member has been physically apprehended</strong>, and how in an age of deepfakes and disinformation, it’s conceivable to construct a false narrative that everyone believes. He even entertains the extreme conspiracy that perhaps Lazarus is <em>“neither wholly real nor entirely fictional, but a shapeshifting myth”</em> serving multiple agendas (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://dev.to/scofieldidehen/the-lazarus-hackers-everything-you-know-is-a-lie-l05#:~:text=To%20grasp%20how%20complicated%20this,incompetence%20or%20advance%20hidden%20agendas">The Lazarus Hackers: Everything You Know Is a Lie - DEV Community</a>).</p><p>That is likely too extreme – discounting extensive forensic evidence and first-hand accounts of North Korean cyber operations. North Korean defector testimonies and intelligence reports consistently describe a government program training hundreds of <strong>elite hackers (Bureau 121)</strong> who are sent abroad to earn foreign currency by any means necessary. The Lazarus phenomenon fits into that known puzzle. <strong>However, the kernel of truth in the “bogeyman” critique is this:</strong> the legend of Lazarus sometimes <strong>overshadows systemic issues</strong> that enable these hacks in the first place. It’s easier to focus on an external enemy than to admit uncomfortable truths about the cryptocurrency industry’s vulnerabilities or one’s own security posture.</p><h2 id="h-attribution-and-accountability-beyond-the-lazarus-narrative" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Attribution and Accountability: Beyond the Lazarus Narrative</h2><p>Ultimately, two things can be true at once. <strong>Lazarus Group (and its North Korean affiliates) can indeed be responsible for many of these crypto heists, <em>and</em></strong> the specter of Lazarus can be wielded as a convenient shield against deeper accountability. Recognizing Lazarus’s role should not preclude us from asking tough questions about why these attacks succeed with such regularity.</p><p>For one, the <strong>cryptocurrency sector’s security standards</strong> have often fallen short. Many exchanges that lost funds to Lazarus had <strong>single points of failure</strong> – whether an unsecured hot wallet, an insufficiently vetted software update, or an overly trusting internal culture susceptible to social engineering. The fact that Lazarus keeps breaching major firms suggests that basic best practices (like strict multi-sig controls, out-of-band transaction verification, employee phishing training, etc.) were not rigorously implemented or were flawed. Bybit’s case revealed a flaw in a critical procedure that should have been caught in security audits (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://cointelegraph.com/learn/articles/how-the-bybit-hack-happened#:~:text=The%20February%202025%20Bybit%20hack,contract%20logic%20and%20offchain%20infrastructure">How the Bybit hack happened: inside the $1.5 billion crypto heist</a>). Similarly, the Ronin bridge hack was enabled by having a majority of validator keys accessible and a lapse in monitoring. When we pin it all on Lazarus’s cunning, there’s a risk of absolving the victims for mistakes that, if corrected, could prevent the next Lazarus-style attack.</p><p>There’s also the broader ecosystem problem: <strong>DeFi protocols and cross-chain bridges</strong> boomed in usage (with billions in value) but often had immature security. Lazarus astutely exploited this gap. The crypto community must address these <em>systemic vulnerabilities</em> – through better code audits, bug bounties, decentralized security mechanisms – rather than simply lamenting that North Korean spies are crafty. As one Chainalysis report noted, <strong>North Korea’s hackers have demonstrated a “consistent ability to adapt and exploit vulnerabilities in the cryptocurrency ecosystem” (</strong><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.trmlabs.com/resources/blog/the-bybit-hack-following-north-koreas-largest-exploit#:~:text=exploits%2C%20North%20Korean%20hackers%20compromised,USD%20600%20million%20in%20cryptocurrency"><strong>The Bybit Hack: Following North Korea’s Largest Exploit | TRM Insights</strong></a><strong>)</strong>. That implies the ecosystem has plenty of exploitable cracks. Fixing those cracks is as important as hunting the culprits.</p><p>From a law enforcement perspective, attributing to Lazarus is just step one. The harder challenge is how to <em>deter and disrupt</em> them. Sanctions on mixer services and seizures of stolen funds (where possible) have been one approach – for example, the U.S. Treasury sanctioned the <strong>Tornado Cash</strong> mixer after it was used heavily by Lazarus, and reportedly helped recover some funds from the Ronin hack by tracking and pressure on intermediaries. However, North Korea continues to find ways around these measures, using ever more convoluted laundering and even emerging tech like DeFi. <strong>The cat-and-mouse game continues</strong>, and every successful attribution needs to be followed by concrete action (indictments, asset freezes, diplomatic pressure on countries harboring Lazarus operatives, etc.) to have any meaning.</p><p>For the private sector, a candid post-mortem after a hack is essential. Some exchanges have started to own up to shortcomings. Following the Bybit hack, <strong>Bybit’s CEO Ben Zhou publicly explained that the breach occurred during a routine wallet transfer and vowed to overhaul their multisig processes</strong>. They even offered a $140 million bounty to encourage global experts to track the stolen crypto (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.reddit.com/r/CryptoCurrency/comments/1iw64lm/bybit_launches_140m_bounty_to_track_down_crypto/#:~:text=Bybit%20launches%20%24140m%20bounty%20to,wallet%20during%20a%20routine%20transfer">Bybit launches $140m bounty to track down crypto heist - Reddit</a>). Such transparency and proactive measures are crucial. It acknowledges that while Lazarus’s involvement is likely, it doesn’t change the fact that something in Bybit’s system failed. <strong>Honest accountability</strong> and improvement will ultimately do more to protect users than simply banking on attribution to ward off criticism.</p><h2 id="h-conclusion-a-nuanced-threat-landscape" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Conclusion: A Nuanced Threat Landscape</h2><p>In the lore of cybercrime, the Lazarus Group has earned a place as a sort of digital super-villain – <strong>audacious, resourceful, and working at the behest of a rogue nation with little to lose</strong>. The attribution of many cryptocurrency exchange hacks to Lazarus is backed by considerable evidence: telltale malware, familiar phishing ruses, and money trails that all lead to Pyongyang’s door. The danger Lazarus poses is very real; few others have combined state support with criminal techniques so effectively, stealing <strong>coins at a scale that can shake markets and international security</strong> (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://cointelegraph.com/learn/articles/how-the-bybit-hack-happened#:~:text=The%20aftermath%20was%20equally%20dramatic,history%20of%20targeting%20financial%20institutions">How the Bybit hack happened: inside the $1.5 billion crypto heist</a>). Dismissing the Lazarus attribution as pure myth would be folly given what we know.</p><p>However, as with any complex issue, <strong>the truth is not black-and-white</strong>. Lazarus can be a <em>real threat</em> <strong>and</strong> a <em>scapegoat in some narratives</em>. The consistency of blaming Lazarus invites us to scrutinize the attribution process itself – to ensure that it remains rigorous and evidence-based, not swayed by convenience or fear. It also nudges us to see the bigger picture: North Korea’s hackers thrive not just because of their skill, but because the systems they target often have cracks to exploit. Those cracks are in our power to fix.</p><p>In calling out Lazarus, we must avoid <strong>creating a “myth of invincibility”</strong> around them that stifles criticism of security lapses or that fuels fatalism (“if a nation-state wants to hack us, why bother trying to stop it?”). Instead, the Lazarus story should galvanize better defenses. It should also remind us that <strong>attribution is a starting point, not an end point</strong> – a clue toward justice, not an excuse to close a case. As investigators peel back the layers of each hack, they must remain open to all possibilities, even ones that challenge the prevailing Lazarus narrative.</p><p>Is Lazarus a pawn in global cyber games? In some ways yes – they are wielded by their government for profit, and wielded in turn in international discourse as the face of crypto-crime. Is Lazarus a scapegoat? At times, perhaps, when their name is used too liberally. But importantly, <strong>Lazarus is also a mirror</strong>. The frenzy around their exploits reflects our collective anxieties: about the precariousness of digital assets, the opacity of state-sponsored crime, and the thin line between cybersecurity and geopolitics. In that mirror we see a cautionary tale of <strong>vulnerability in the digital age</strong>, as well as our tendency to seek simple villains for complex failures.</p><p>In the end, understanding the truth about Lazarus Group – stripped of both hype and denial – can help the crypto industry and governments alike respond more intelligently. It means <strong>neither underestimating nor mythologizing the threat</strong>. It means investing in stronger security and oversight for crypto platforms, so that even an elite adversary finds no easy pickings. And it means maintaining a critical eye on attribution: demanding evidence, cross-checking facts, and recognizing the limits of our knowledge. Only then can we ensure that when Lazarus (or any other group) strikes again, we’ll be ready to catch them in the act – or better yet, stop them at the gate – rather than just assigning a familiar blame after the fact.</p><p><strong>Sources:</strong> The investigation draws on multiple reports and expert analyses, including Group-IB’s <em>“Lazarus Arisen”</em> intelligence report (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.group-ib.com/blog/lazarus/#:~:text=Group,they%20have%20planned%20to%20attack">LAZARUS ARISEN | Group-IB Blog</a>) (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.c4isrnet.com/home/2017/06/02/new-report-details-clear-attribution-of-lazarus-group-hacks-to-north-korean-military/#:~:text=A%20report%20published%20this%20week,cyberattacks%20and%20espionage%20against%20enemies">New report details &apos;clear attribution&apos; of Lazarus Group hacks to North Korean military</a>), the BBC’s <em>Lazarus Heist</em> coverage, U.N. findings on DPRK cyber operations (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.reuters.com/technology/record-breaking-2022-north-korea-crypto-theft-un-report-2023-02-06/#:~:text=,member%20states%20and%20cybersecurity%20firms">Exclusive: Record-breaking 2022 for North Korea crypto theft, UN report says | Reuters</a>), and numerous cybersecurity research publications. Technical details and attribution evidence are sourced from blockchain analytics firms (TRM Labs, Elliptic, Chainalysis) (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.trmlabs.com/resources/blog/the-bybit-hack-following-north-koreas-largest-exploit#:~:text=Through%20blockchain%20intelligence%2C%20TRM%20Labs,the%20heist%20to%20North%20Korea">The Bybit Hack: Following North Korea’s Largest Exploit | TRM Insights</a>) (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.elliptic.co/blog/bybit-hack-largest-in-history#:~:text=Elliptic%20has%20attributed%20the%20Bybit,reportedly%20spent%20on%20the%20country%E2%80%99s">The largest theft in history - following the money trail from the Bybit Hack</a>), law enforcement statements (FBI, DOJ) (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.fbi.gov/news/press-releases/fbi-confirms-lazarus-group-cyber-actors-responsible-for-harmonys-horizon-bridge-currency-theft#:~:text=As%20a%20follow,reported%20on%20June%2024%2C%202022">FBI Confirms Lazarus Group Cyber Actors Responsible for Harmony&apos;s Horizon Bridge Currency Theft — FBI</a>) (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.justice.gov/archives/opa/pr/three-north-korean-military-hackers-indicted-wide-ranging-scheme-commit-cyberattacks-and#:~:text=A%20federal%20indictment%20unsealed%20today,fraudulently%20market%20a%20blockchain%20platform">Office of Public Affairs | Three North Korean Military Hackers Indicted in Wide-Ranging Scheme to Commit Cyberattacks and Financial Crimes Across the Globe | United States Department of Justice</a>), and cybersecurity experts’ writings (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://dev.to/scofieldidehen/the-lazarus-hackers-everything-you-know-is-a-lie-l05#:~:text=,%E2%80%9D">The Lazarus Hackers: Everything You Know Is a Lie - DEV Community</a>) (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.malwarebytes.com/blog/news/2022/12/lazarus-group-uses-fake-cryptocurrency-apps-to-plant-applejeus-malware#:~:text=Since%202018%2C%20one%20of%20Lazarus,can%20initiate%20fraudulent%20cryptocurrency%20transactions">Lazarus group uses fake cryptocurrency apps to plant AppleJeus malware</a>). These sources collectively underpin the examination of Lazarus Group’s alleged tactics and the scrutiny of the attribution process.</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[Ethereum Governance: What Snapshot, Tally, Aragon, and Agora Are]]></title>
            <link>https://paragraph.com/@defi-in-security/ethereum-governance-what-snapshot-tally-aragon-and-agora-are</link>
            <guid>adnvcirjLZCOucAMZesq</guid>
            <pubDate>Sun, 16 Feb 2025 15:32:51 GMT</pubDate>
            <description><![CDATA[Ethereum has long been at the forefront of decentralized decision-making, but governance remains a complex and evolving challenge. While true decentralized governance is still a work in progress, various platforms have emerged to facilitate community-driven proposals and voting. Snapshot, Tally, Aragon, and Agora each provide unique solutions, yet they are not replacements for an on-chain governance system. Snapshot is one of the most widely used off-chain voting mechanisms in Ethereum. It al...]]></description>
            <content:encoded><![CDATA[<p>Ethereum has long been at the forefront of decentralized decision-making, but governance remains a complex and evolving challenge. While true <strong>decentralized governance</strong> is still a work in progress, various platforms have emerged to facilitate community-driven proposals and voting. Snapshot, Tally, Aragon, and Agora each provide unique solutions, yet they are not replacements for an on-chain governance system.</p><p><strong>Snapshot</strong> is one of the most widely used off-chain voting mechanisms in Ethereum. It allows users to vote on proposals based on token ownership, but without executing transactions on the blockchain. This makes governance fast and gas-free, yet non-binding, as execution still relies on trust in multisigs or centralized actors.</p><p><strong>Tally</strong> takes a different approach, offering <strong>on-chain governance for DAOs</strong>. It integrates directly with smart contracts, ensuring that votes result in actual protocol changes without intermediary trust. While it provides stronger decentralization guarantees than Snapshot, it requires participants to pay gas fees for their votes, which can be a barrier.</p><p><strong>Aragon</strong> is a full-fledged DAO framework, enabling organizations to create governance structures with smart contracts that handle voting, fund management, and role assignments. It allows more automation but can be complex to set up and govern effectively.</p><p><strong>Agora</strong> is another governance tool often linked to DAOs, focusing on creating transparent and verifiable voting mechanisms. While similar in concept to Snapshot, its goal is to improve voting integrity and accessibility for different communities.</p><p>While these tools enable decentralized decision-making, they do not equate to full <strong>decentralized governance</strong>. Most rely on off-chain signaling, social consensus, or multi-signature execution rather than automatic enforcement through smart contracts. They serve as polling mechanisms, gathering community sentiment and guiding protocol decisions, but <strong>true on-chain governance remains limited</strong> to specific DAOs and protocols with built-in execution logic.</p><p>The discussion around Ethereum governance continues, as projects explore hybrid models combining <strong>off-chain coordination with on-chain enforcement</strong>. While no single tool provides a perfect solution, these platforms play a critical role in shaping the future of decentralized decision-making in Ethereum and beyond.</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[New Age Web3 DevSecOps Features]]></title>
            <link>https://paragraph.com/@defi-in-security/new-age-web3-devsecops-features</link>
            <guid>Fn1TrVyeZmI4pa8bM3jR</guid>
            <pubDate>Wed, 13 Nov 2024 18:56:36 GMT</pubDate>
            <description><![CDATA[In the rapidly evolving landscape of web3 decentralized applications (dApps), ensuring security throughout the development and operational lifecycle is paramount. Two innovative technologies can significantly enhance DevSecOps practices for web3 dApps:On-chain MD5 Hash Verification of Web Content: An idea proposed by 0xKoda, which involves storing MD5 hashes of approved webpage content on the blockchain to verify the integrity of web interfaces.Software Bill of Materials (SBOM): A comprehensi...]]></description>
            <content:encoded><![CDATA[<p>In the rapidly evolving landscape of web3 decentralized applications (dApps), ensuring security throughout the development and operational lifecycle is paramount. Two innovative technologies can significantly enhance DevSecOps practices for web3 dApps:</p><ol><li><p><strong>On-chain MD5 Hash Verification of Web Content</strong>: An idea proposed by 0xKoda, which involves storing MD5 hashes of approved webpage content on the blockchain to verify the integrity of web interfaces.</p></li><li><p><strong>Software Bill of Materials (SBOM)</strong>: A comprehensive inventory of all software components used in an application, facilitating vulnerability management and supply chain security.</p></li></ol><p>Combining these technologies can create a robust solution to address critical DevSecOps challenges in web3 dApps. Below, we&apos;ll explore how each technology benefits DevSecOps and product security, and how they can be integrated to solve prevalent security issues.</p><hr><p><strong>1. On-chain MD5 Hash Verification of Web Content</strong></p><p><em>GitHub Repository</em>: <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/0xKoda/verifi-web">0xKoda/verifi-web</a></p><p><strong>Benefits for DevSecOps and Product Security:</strong></p><ul><li><p><strong>Integrity Verification</strong>: By storing MD5 hashes of approved web content on-chain, developers can ensure that users interact with authentic and untampered interfaces. This prevents malicious actors from introducing phishing sites or injecting harmful code.</p></li><li><p><strong>User Trust</strong>: An extension that checks the current webpage&apos;s hash against the on-chain stored hash enhances user confidence. Users receive real-time alerts if discrepancies are detected before connecting their wallets or submitting sensitive information.</p></li><li><p><strong>Decentralized Assurance</strong>: Leveraging the blockchain&apos;s immutable nature ensures that the approved content&apos;s hash is tamper-proof, providing a reliable source of truth for verification processes.</p></li></ul><p><strong>Application in Web3 dApps:</strong></p><p>In the context of web3 dApps, where users often interact with smart contracts through web interfaces, ensuring the authenticity of these interfaces is crucial. On-chain hash verification protects against:</p><ul><li><p><strong>Phishing Attacks</strong>: Prevents users from falling victim to fake websites designed to steal private keys or seed phrases.</p></li><li><p><strong>Content Tampering</strong>: Detects unauthorized changes to the web interface that could introduce vulnerabilities or malicious behaviors.</p></li></ul><hr><p><strong>2. Software Bill of Materials (SBOM)</strong></p><p><em>Overview by CISA</em>: SBOM is a nested inventory of all software components, including open-source and third-party libraries, used in building an application.</p><p><strong>Benefits for DevSecOps and Product Security:</strong></p><ul><li><p><strong>Transparency</strong>: Provides a detailed inventory of all components, enabling teams to understand the software&apos;s makeup fully.</p></li><li><p><strong>Vulnerability Management</strong>: Identifies known vulnerabilities in components through tools like the Vulnerability Exploitability eXchange (VEX), allowing for proactive remediation.</p></li><li><p><strong>Compliance and Risk Management</strong>: Helps meet regulatory requirements and manage supply chain risks by tracking component licenses and origins.</p></li></ul><p><strong>Application in Web3 dApps:</strong></p><p>Web3 dApps often rely on numerous open-source libraries and dependencies. SBOMs enable developers to:</p><ul><li><p><strong>Track Dependencies</strong>: Keep an accurate record of all software components and their versions.</p></li><li><p><strong>Detect Vulnerabilities</strong>: Use SBOMs in conjunction with vulnerability databases to identify and address security flaws in dependencies.</p></li><li><p><strong>Facilitate Incident Response</strong>: Quickly assess impact and scope when vulnerabilities are disclosed, streamlining the patching process.</p></li></ul><hr><p><strong>Integrating Both Technologies for a Comprehensive DevSecOps Solution</strong></p><p><strong>Combining On-chain Hash Verification and SBOM:</strong></p><p>By integrating the on-chain hash verification of web content with SBOM practices, we can create a multi-layered security approach:</p><ol><li><p><strong>Enhanced Integrity Verification</strong>:</p><ul><li><p><strong>Web Interface</strong>: Store hashes of the approved web interface on-chain.</p></li><li><p><strong>Application Components</strong>: Include hashes of critical application binaries and scripts in the SBOM.</p></li><li><p><strong>Combined Verification</strong>: Extend the browser extension to check both the web content and the underlying application components against the on-chain hashes and SBOM data.</p></li></ul></li><li><p><strong>Real-time Vulnerability Assessment</strong>:</p><ul><li><p><strong>SBOM Integration</strong>: Incorporate SBOM data into the verification process to check for known vulnerabilities using VEX advisories.</p></li><li><p><strong>User Alerts</strong>: Notify users if they are interacting with a dApp that includes vulnerable components, allowing them to make informed decisions.</p></li></ul></li><li><p><strong>Automated CI/CD Pipeline Enhancements</strong>:</p><ul><li><p><strong>SBOM Generation</strong>: Automate the creation of SBOMs during the build process.</p></li><li><p><strong>On-chain Updates</strong>: Deploy updated hashes and SBOM data to the blockchain as part of the release pipeline.</p></li><li><p><strong>Continuous Monitoring</strong>: Implement tools that continuously monitor for new vulnerabilities affecting components listed in the SBOM.</p></li></ul></li></ol><p><strong>Additional Technologies to Enhance the Solution:</strong></p><ul><li><p><strong>Smart Contracts for SBOM Management</strong>: Use smart contracts to manage SBOM data on-chain, providing decentralized access control and auditability.</p></li><li><p><strong>Decentralized Identity (DID)</strong>: Implement DID standards to verify the identities of developers and contributors, enhancing trust in the SBOM and hash data.</p></li><li><p><strong>Security Orchestration, Automation, and Response (SOAR)</strong>: Integrate SOAR platforms to automate responses to detected security issues, such as revoking compromised hashes or notifying stakeholders.</p></li><li><p><strong>Immutable Logs and Auditing</strong>: Leverage blockchain&apos;s immutable ledger to maintain tamper-proof logs of changes to SBOMs and hash records, aiding in compliance and forensic analysis.</p></li></ul><hr><p><strong>Addressing DevSecOps Challenges with the Integrated Solution</strong></p><p><strong>1. Supply Chain Security:</strong></p><ul><li><p><strong>Problem</strong>: Hidden vulnerabilities in third-party components can compromise the entire application.</p></li><li><p><strong>Solution</strong>: SBOM provides visibility into all components, and on-chain storage ensures that only verified versions are used.</p></li></ul><p><strong>2. Phishing and Interface Tampering:</strong></p><ul><li><p><strong>Problem</strong>: Users may be tricked into interacting with malicious interfaces that mimic legitimate dApps.</p></li><li><p><strong>Solution</strong>: On-chain hash verification alerts users to discrepancies, preventing fraudulent interactions.</p></li></ul><p><strong>3. Vulnerability Management:</strong></p><ul><li><p><strong>Problem</strong>: Keeping up with vulnerabilities in dependencies is challenging.</p></li><li><p><strong>Solution</strong>: Automated SBOM analysis with VEX integration ensures timely detection and remediation.</p></li></ul><p><strong>4. Regulatory Compliance:</strong></p><ul><li><p><strong>Problem</strong>: Meeting compliance requirements for software transparency and security is complex.</p></li><li><p><strong>Solution</strong>: SBOMs facilitate compliance by documenting all software components and associated licenses.</p></li></ul><p><strong>5. User Trust and Adoption:</strong></p><ul><li><p><strong>Problem</strong>: Security concerns can hinder user adoption of web3 dApps.</p></li><li><p><strong>Solution</strong>: Providing transparent security measures builds user confidence and promotes wider adoption.</p></li></ul><hr><p><strong>Conclusion</strong></p><p>By integrating the on-chain MD5 hash verification of web content with comprehensive SBOM practices, web3 dApp developers can significantly enhance their DevSecOps capabilities. This combined approach addresses critical security challenges by ensuring the integrity of web interfaces, managing vulnerabilities in software components, and fostering user trust through transparency.</p><p><strong>Key Takeaways:</strong></p><ul><li><p><strong>Multi-layered Security</strong>: Combining content integrity checks with detailed component inventories provides robust protection against a range of security threats.</p></li><li><p><strong>Blockchain Benefits</strong>: Leveraging the blockchain for storing hashes and SBOM data ensures immutability, transparency, and decentralized verification.</p></li><li><p><strong>Proactive Risk Management</strong>: Automated tools and processes enable teams to detect and address vulnerabilities before they can be exploited.</p></li><li><p><strong>Enhanced User Experience</strong>: By safeguarding users against malicious activities, developers can improve the overall experience and reliability of web3 dApps.</p></li></ul><p>Implementing this integrated solution requires collaboration across development, security, and operations teams, embracing DevSecOps principles to embed security into every stage of the software lifecycle. As the web3 ecosystem continues to grow, adopting such comprehensive security measures will be crucial for sustaining trust and ensuring the longevity of decentralized applications.</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://officercia.mirror.xyz/hd13Evk_caRmfKu4d0P9S4W63Tic-sMSLX9y71-CqjM">Special thanks to @officercia</a></p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[Roles in SonarQube 9.9: Optimizing Access for DevSecOps Teams]]></title>
            <link>https://paragraph.com/@defi-in-security/roles-in-sonarqube-9-9-optimizing-access-for-devsecops-teams</link>
            <guid>SBBJiiB1iQ1ZsZEtAcFV</guid>
            <pubDate>Thu, 07 Nov 2024 23:07:10 GMT</pubDate>
            <description><![CDATA[With the increasing demand for code security and quality control in modern DevSecOps teams, tools like SonarQube have become essential. SonarQube 9.9 introduces an improved system of roles and permissions, allowing for flexible access distribution among team members. A clear understanding and correct management of roles can enhance both security and transparency, ensuring DevSecOps teams have the right levels of access to project settings and data without compromising confidentiality or quali...]]></description>
            <content:encoded><![CDATA[<p>With the increasing demand for code security and quality control in modern DevSecOps teams, tools like SonarQube have become essential. SonarQube 9.9 introduces an improved system of roles and permissions, allowing for flexible access distribution among team members. A clear understanding and correct management of roles can enhance both security and transparency, ensuring DevSecOps teams have the right levels of access to project settings and data without compromising confidentiality or quality profile integrity.</p><h4 id="h-key-roles-and-their-capabilities" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Key Roles and Their Capabilities</h4><p>SonarQube offers multiple access levels, from basic project result viewing to full control over profiles and projects. Here’s a breakdown of the key roles and their specific capabilities.</p><ol><li><p><strong>Project Viewer</strong></p><ul><li><p><strong>Role Purpose</strong>: Designed for team members needing access to scan results and code quality insights without the ability to alter project settings.</p></li><li><p><strong>Capabilities</strong>:</p><ul><li><p>View project analysis reports and metrics.</p></li><li><p>Access the assigned Quality Profiles and rules applied to the project.</p></li></ul></li><li><p><strong>Limitations</strong>:</p><ul><li><p>No ability to modify project settings, change Quality Profiles, or manage Quality Gates.</p></li></ul></li><li><p><strong>Ideal Use Case</strong>: Suitable for stakeholders or auditors who need visibility into project status without altering configurations.</p></li></ul></li><li><p><strong>Project Admin</strong></p><ul><li><p><strong>Role Purpose</strong>: Suitable for users responsible for managing specific projects, including setting quality and performance metrics.</p></li><li><p><strong>Capabilities</strong>:</p><ul><li><p>Full access to project settings, including the selection of Quality Profiles and Quality Gates.</p></li><li><p>Ability to include or exclude files from analysis.</p></li><li><p>Configure project-specific thresholds and acceptable metric values.</p></li></ul></li><li><p><strong>Limitations</strong>:</p><ul><li><p>Cannot alter Quality Profiles directly (rule activation requires Quality Profile Admin rights).</p></li></ul></li><li><p><strong>Ideal Use Case</strong>: For managing individual projects that require custom analysis setup to meet particular standards (e.g., projects with strict regulatory requirements).</p></li></ul></li><li><p><strong>Quality Profile Admin</strong></p><ul><li><p><strong>Role Purpose</strong>: Designed for users responsible for creating and maintaining custom Quality Profiles shared across multiple projects.</p></li><li><p><strong>Capabilities</strong>:</p><ul><li><p>Create, edit, and delete Quality Profiles.</p></li><li><p>Activate or deactivate rules within profiles.</p></li><li><p>Develop specialized profiles for different languages to meet specific security or coding style standards.</p></li></ul></li><li><p><strong>Limitations</strong>:</p><ul><li><p>No access to individual project settings.</p></li></ul></li><li><p><strong>Ideal Use Case</strong>: Managing corporate code quality standards aligned with DevSecOps policies. For instance, creating a profile that aligns with OWASP standards for Java and applying it to multiple projects.</p></li></ul></li><li><p><strong>Admin System</strong></p><ul><li><p><strong>Role Purpose</strong>: Assigned to system administrators who require full control over the entire SonarQube installation.</p></li><li><p><strong>Capabilities</strong>:</p><ul><li><p>Full access to all settings, projects, and profiles.</p></li><li><p>User management and role assignment.</p></li><li><p>Configuration of system-wide parameters, such as security policies and audit settings.</p></li></ul></li><li><p><strong>Limitations</strong>: No limitations; this role requires high trust.</p></li><li><p><strong>Ideal Use Case</strong>: For overall SonarQube infrastructure management, including deployment, monitoring, and maintenance tasks, as well as license management and scalability configurations.</p></li></ul></li></ol><h4 id="h-role-distribution-in-devsecops" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Role Distribution in DevSecOps</h4><p>For DevSecOps teams, a well-organized role distribution can streamline project management and improve security, reducing the risk of unauthorized changes to quality profiles or critical security rules.</p><ol><li><p><strong>Adhering to the Principle of Least Privilege</strong>. Assign team members only the access they need for their roles. This minimizes the risk of accidental profile changes or rule deletions.</p></li><li><p><strong>Using Custom Quality Profiles for Different Teams and Projects</strong>. Separating profiles by task allows DevSecOps teams to implement specific standards and apply updates quickly across related projects.</p></li><li><p><strong>Regular Auditing of Roles</strong>. Periodically review which users hold administrative rights and adjust as projects or teams evolve.</p></li><li><p><strong>Leveraging Quality Gates for DevSecOps Goals</strong>. Quality Gates are particularly useful for checking security and quality compliance. For example, set threshold levels for vulnerabilities and test coverage so projects can only progress in CI/CD if they meet the gate’s criteria.</p></li></ol><h4 id="h-conclusion" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Conclusion</h4><p>Roles in SonarQube 9.9 enable flexible responsibility distribution and strong project governance for DevSecOps teams. By following the principles of least privilege and regular role auditing, organizations can maintain a high level of security and transparency, adapting the development process to meet specific code quality and data protection needs.</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[Applying PCI DSS in Web3]]></title>
            <link>https://paragraph.com/@defi-in-security/applying-pci-dss-in-web3</link>
            <guid>YodNJxNuSQINYcN9x0JK</guid>
            <pubDate>Tue, 15 Oct 2024 22:40:06 GMT</pubDate>
            <description><![CDATA[In the evolving landscape of Web3, where decentralization, blockchain technology, and digital assets are becoming increasingly prominent, security remains a critical concern. While Web3 promises to revolutionize industries by offering greater transparency, autonomy, and innovation, it also introduces new risks, especially when handling sensitive data and financial transactions. Payment Card Industry Data Security Standard (PCI DSS), traditionally associated with the protection of cardholder d...]]></description>
            <content:encoded><![CDATA[<blockquote><p>In the evolving landscape of Web3, where decentralization, blockchain technology, and digital assets are becoming increasingly prominent, security remains a critical concern. While Web3 promises to revolutionize industries by offering greater transparency, autonomy, and innovation, it also introduces new risks, especially when handling sensitive data and financial transactions. Payment Card Industry Data Security Standard (PCI DSS), traditionally associated with the protection of cardholder data in centralized financial systems, is highly relevant in this new context as well. The core principles of PCI DSS — such as securing sensitive information, controlling access, and regular auditing — can be applied to safeguard critical financial and user/server data within Web3 ecosystems, helping mitigate threats and ensuring compliance in decentralized applications and blockchain-driven environments. Understanding and implementing PCI DSS standards in Web3 could be the key to establishing trust, preventing breaches, and protecting both users and assets in this digital frontier.</p></blockquote><p>PCI DSS (Payment Card Industry Data Security Standard) is a security standard designed to protect cardholder data and prevent information leaks. Version 4.0 was released in 2022 and represents a significant update compared to version 3.2.1. Let&apos;s consider the key requirements, as well as the procedures auditors may ask for in both versions.</p><h3 id="h-key-changes-in-pci-dss-40" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Key Changes in PCI DSS 4.0</h3><p>Version 4.0 focuses on improving the flexibility of approaches, adapting to rapidly changing technological landscapes, and enhancing security controls. Unlike version 3.x, version 4.0 introduces more adaptive processes and enhanced control capabilities. Changes include:</p><ul><li><p>A new flexible approach to meeting requirements, allowing organizations to implement controls based on their own procedures.</p></li><li><p>Stricter authentication requirements.</p></li><li><p>Improved risk management.</p></li></ul><p>Now let’s look at the key requirements that are essential for auditors in both versions.</p><h3 id="h-main-requirements-of-pci-dss-3x-and-40" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Main Requirements of PCI DSS 3.x and 4.0</h3><ol><li><p><strong>Protecting Cardholder Data</strong>:</p><ul><li><p><strong>Procedures</strong>: Encryption of data, protection of data at rest and in transit, monitoring access to data storage systems. Auditors ask for the encryption policy and how sensitive data is protected.</p></li></ul></li><li><p><strong>Network Segmentation</strong>:</p><ul><li><p><strong>Procedures</strong>: Auditors verify that proper network segmentation is in place to isolate cardholder data from the rest of the IT infrastructure. They may request network diagrams and documented segmentation plans.</p></li></ul></li><li><p><strong>Access Control and Authentication</strong>:</p><ul><li><p><strong>Procedures</strong>: Includes least privilege access control, multi-factor authentication (MFA) for all users with card data access. Auditors check account management procedures, privilege assignments, and MFA enforcement.</p></li></ul></li><li><p><strong>Vulnerability and Patch Management</strong>:</p><ul><li><p><strong>Procedures</strong>: Regular vulnerability scanning, patch management, and updates. Auditors request vulnerability scan reports, patch logs, and procedures for vulnerability management.</p></li></ul></li><li><p><strong>Event Monitoring and Logging</strong>:</p><ul><li><p><strong>Procedures</strong>: Logs must be collected, stored, and analyzed for suspicious activity. Auditors request log data and procedures for monitoring security events.</p></li></ul></li><li><p><strong>Security Testing and Auditing</strong>:</p><ul><li><p><strong>Procedures</strong>: Regular penetration tests, firewall configuration reviews, and other security measures. Auditors review test documentation and verify that all vulnerabilities have been addressed.</p></li></ul></li><li><p><strong>Staff Training</strong>:</p><ul><li><p><strong>Procedures</strong>: All staff handling cardholder data must receive regular security training. Auditors request evidence of regular training and staff security awareness monitoring.</p></li></ul></li></ol><h3 id="h-additional-requirements-in-pci-dss-40" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Additional Requirements in PCI DSS 4.0</h3><ol><li><p><strong>Risk-Based Approach</strong>:</p><ul><li><p><strong>Procedures</strong>: Organizations must conduct regular risk assessments and develop mitigation plans. Auditors ask for risk assessment plans and analysis of how identified risks are addressed with security measures.</p></li></ul></li><li><p><strong>Dynamic Testing and Continuous Monitoring</strong>:</p><ul><li><p><strong>Procedures</strong>: PCI DSS 4.0 introduces more dynamic processes for security control, such as adaptive system testing methods. Auditors may request evidence of how these new dynamic approaches are used to enhance security.</p></li></ul></li><li><p><strong>Continuous Performance Monitoring</strong>:</p><ul><li><p><strong>Procedures</strong>: 4.0 introduces stricter requirements for continuous monitoring of critical systems, including the use of automation tools for incident tracking. Auditors may request monitoring reports and alerting systems used by the organization.</p></li></ul></li><li><p><strong>Authentication and Identity Management Requirements</strong>:</p><ul><li><p><strong>Procedures</strong>: PCI DSS 4.0 significantly tightens requirements for account management, including additional MFA controls and ensuring least privilege access. Auditors will review the configuration of all accounts, access levels, and authentication settings.</p></li></ul></li></ol><h3 id="h-documents-required-by-auditors" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Documents Required by Auditors:</h3><ol><li><p><strong>Security Policies</strong>: Complete information security policies, including encryption, network segmentation, access control, and authentication policies.</p></li><li><p><strong>Logs</strong>: Security event logs, incident records, authentication logs, and system access logs.</p></li><li><p><strong>Vulnerability Reports</strong>: Results of vulnerability scans, penetration tests.</p></li><li><p><strong>Network Diagrams</strong>: Documented network architectures, segmentation to protect cardholder data.</p></li><li><p><strong>Change Management Documentation</strong>: Procedures for configuration changes and software updates, including patch management.</p></li><li><p><strong>Penetration Testing Reports</strong>: Data from regular system vulnerability testing.</p></li></ol><h3 id="h-what-needs-to-be-provided" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">What Needs to Be Provided:</h3><ul><li><p>Policies for each of the requirements.</p></li><li><p>Proof of procedure execution in the form of logs, reports, test results.</p></li><li><p>Documentation proving regular training and staff awareness programs.</p></li><li><p>Audit reports and self-assessments of PCI DSS compliance.</p></li></ul><p>Following these regulatory procedures ensures compliance with both 3.x and 4.0 versions of PCI DSS and is crucial for successfully passing an audit.</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[Additional IP Pool in Calico]]></title>
            <link>https://paragraph.com/@defi-in-security/additional-ip-pool-in-calico</link>
            <guid>2UcFujjadNvTnjTem7px</guid>
            <pubDate>Tue, 24 Sep 2024 21:56:00 GMT</pubDate>
            <description><![CDATA[In Kubernetes clusters using Calico as the networking solution, you might encounter scenarios where you need to assign different source IP addresses for pods within your internal network. This can help in better traffic management, policy enforcement, or avoiding IP conflicts. This guide will walk you through configuring an additional IP pool in Calico to change the source IP addresses used by pods. We&apos;ll use calicoctl apply -f ippool.yaml to apply the configuration, ensuring that the bl...]]></description>
            <content:encoded><![CDATA[<p>In Kubernetes clusters using Calico as the networking solution, you might encounter scenarios where you need to assign different source IP addresses for pods within your internal network. This can help in better traffic management, policy enforcement, or avoiding IP conflicts.</p><p>This guide will walk you through configuring an additional IP pool in Calico to change the source IP addresses used by pods. We&apos;ll use <code>calicoctl apply -f ippool.yaml</code> to apply the configuration, ensuring that the <code>blockSize</code> parameter in the <code>IPPool</code> manifest is set correctly—specifically, making it smaller (i.e., a larger subnet mask number) than the default Calico block size.</p><h2 id="h-prerequisites" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Prerequisites</h2><p>A running Kubernetes cluster with Calico installed. Access to the cluster using <code>kubectl</code>.<code>calicoctl</code> command-line tool installed and configured to interact with your Calico installation.</p><p>Note: This guide assumes that Calico and its tools are already installed and configured in your cluster.</p><h2 id="h-step-1-understand-the-default-ipam-configuration" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Step 1: Understand the Default IPAM Configuration</h2><p>By default, Calico uses a block size of <code>/26</code> for IP address management. This means each node is assigned IP addresses from a <code>/26</code> subnet, providing 64 IP addresses per node.</p><p>To create smaller blocks and have more granular control over IP allocation, we can define a custom IP pool with a smaller <code>blockSize</code>. This allows for more efficient IP usage and prevents IP exhaustion on nodes with fewer pods.</p><h2 id="h-step-2-create-the-ippool-manifest" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Step 2: Create the IPPool Manifest</h2><p>We&apos;ll create a new IP pool by defining an <code>IPPool</code> in a YAML file named <code>ippool.yaml</code>.</p><p>Here is how to define the IP pool with a custom <code>blockSize</code>:</p><pre data-type="codeBlock" text="apiVersion: projectcalico.org/v3
kind: IPPool
metadata:
  name: custom-ippool
spec:
  cidr: &quot;172.25.0.0/16&quot;
  ipipMode: Never
  vxlanMode: Never
  natOutgoing: true
  blockSize: 28
  disabled: false
  nodeSelector: &quot;!all()&quot;
"><code><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">projectcalico.org/v3</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">IPPool</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">custom-ippool</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">cidr:</span> <span class="hljs-string">"172.25.0.0/16"</span>
  <span class="hljs-attr">ipipMode:</span> <span class="hljs-string">Never</span>
  <span class="hljs-attr">vxlanMode:</span> <span class="hljs-string">Never</span>
  <span class="hljs-attr">natOutgoing:</span> <span class="hljs-literal">true</span>
  <span class="hljs-attr">blockSize:</span> <span class="hljs-number">28</span>
  <span class="hljs-attr">disabled:</span> <span class="hljs-literal">false</span>
  <span class="hljs-string">nodeSelector:</span> <span class="hljs-string">"!all()"</span>
</code></pre><p><code>apiVersion</code>: Specifies the Calico API version (projectcalico.org/v3). Try v1 if fails on applying.<br><code>kind</code>: IPPool indicates that we are defining an IP address pool.<code>metadata.name</code>: A unique name for your IP pool (custom-ippool).<br><code>spec.cidr</code>: The CIDR range for the new IP pool (172.25.0.0/16 in this example).<br><code>spec.blockSize</code>: Set to 28 to define a subnet mask of /28, resulting in blocks of 16 IP addresses per node (smaller than the default /26).<br><code>spec.ipipMode</code> and <code>spec.vxlanMode</code>: Set according to your networking requirements (Never, Always, or CrossSubnet).<br><code>spec.natOutgoing</code>: Set to true to enable outbound NAT for traffic leaving this pool.<br><code>spec.disabled</code>: Set to false to enable the IP pool.<br><code>nodeSelector</code>: to <code>!all()</code> so the selector matches no nodes, the IPPool will not be used automatically and, unlike setting <code>disabled: true</code>, it can still be used for manual assignments.</p><p>Reference:</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://docs.tigera.io/archive/v3.19/reference/resources/ippool">https://docs.tigera.io/archive/v3.19/reference/resources/ippool</a></p><p>Note: The <code>blockSize</code> parameter specifies the size of IP address blocks assigned to each node. A smaller block size means each node gets a smaller range of IP addresses, which can improve IP utilization in clusters where nodes run a small number of pods.</p><h2 id="h-step-3-apply-the-ip-pool-configuration" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Step 3: Apply the IP Pool Configuration</h2><p>Use <code>calicoctl</code> to apply the new IP pool configuration to your cluster:</p><p><code>calicoctl apply -f ippool.yaml</code></p><p>Using <code>calicoctl</code> ensures that the configuration is validated before being applied, helping to catch any misconfigurations.</p><p>Important: Ensure that <code>calicoctl</code> is configured to communicate with your datastore (e.g., etcd or the Kubernetes API server). If using Kubernetes API datastore, set the necessary environment variables or use the <code>--config</code> flag with a configuration file.</p><h2 id="h-step-4-verify-the-ip-pool-configuration" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Step 4: Verify the IP Pool Configuration</h2><p>After applying the IP pool, verify that it has been correctly configured and is active.</p><p>List all IP pools:</p><p><code>calicoctl get ippools</code></p><p>You should see <code>custom-ippool</code> listed with the correct CIDR and settings.</p><p>To get detailed information about the pool:</p><p><code>calicoctl get ippool custom-ippool -o yaml</code></p><p>Ensure that the <code>blockSize</code> is set to 28 and other parameters are as intended.</p><h2 id="h-step-5-assign-pods-to-the-new-ip-pool-using-annotations" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Step 5: Assign Pods to the New IP Pool Using Annotations</h2><p>To have pods use IP addresses from the new IP pool, you can specify the IP pool in the pod&apos;s annotations.</p><p>In your pod or deployment manifest, add the following annotation:</p><pre data-type="codeBlock" text="metadata:
  annotations:
    &apos;cni.projectcalico.org/ipv4pools&apos;: &apos;[&quot;custom-pool&quot;]&apos;
"><code><span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">annotations:</span>
    <span class="hljs-attr">'cni.projectcalico.org/ipv4pools':</span> <span class="hljs-string">'["custom-pool"]'</span>
</code></pre><p>Example Pod Manifest:</p><pre data-type="codeBlock" text="apiVersion: v1
kind: Pod
metadata:
  name: test-pod
  annotations:
    &apos;cni.projectcalico.org/ipv4pools&apos;: &apos;[&quot;custom-pool&quot;]&apos;
spec:
  containers:
    - name: nginx
      image: nginx
      ports:
        - containerPort: 80
"><code><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Pod</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">test-pod</span>
  <span class="hljs-attr">annotations:</span>
    <span class="hljs-attr">'cni.projectcalico.org/ipv4pools':</span> <span class="hljs-string">'["custom-pool"]'</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">containers:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">nginx</span>
      <span class="hljs-attr">image:</span> <span class="hljs-string">nginx</span>
      <span class="hljs-attr">ports:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">containerPort:</span> <span class="hljs-number">80</span>
</code></pre><p>Note: The annotation <code>cni.projectcalico.org/ipv4pools</code> tells Calico to assign an IP address from the specified IP pool “custom-pool” to the pod.</p><h2 id="h-step-6-deploy-the-test-pod" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Step 6: Deploy the Test Pod</h2><p>Apply the pod manifest:</p><p><code>kubectl apply -f test-pod.yaml</code></p><h2 id="h-step-7-verify-the-pods-ip-address" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Step 7: Verify the Pod&apos;s IP Address</h2><p>Check the pod&apos;s IP address:</p><p><code>kubectl get pod test-pod -o wide</code></p><p>The IP address should be within the <code>172.25.0.0/16</code> range.</p><h2 id="h-step-8-confirm-block-size-allocation" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Step 8: Confirm Block Size Allocation</h2><p>To ensure that the <code>blockSize</code> parameter is in effect, you can check the IP blocks allocated to nodes.</p><p>Use the following command:</p><p><code>calicoctl get ipamblocks -o yaml</code></p><p>Look for blocks within <code>172.25.0.0/16</code> assigned to nodes and verify that they have a <code>/28</code> mask.</p><h2 id="h-step-9-monitor-and-troubleshoot" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Step 9: Monitor and Troubleshoot</h2><p>Monitor Calico and the cluster to ensure the new IP pool is functioning as expected.</p><p>Check Calico Node Logs:</p><p><code>kubectl logs -n kube-system -l k8s-app=calico-node</code></p><p>Describe the Pod:</p><p><code>kubectl describe pod test-pod</code></p><p>Check for any events or errors related to IP assignment.</p><p>Check Calico IPAM Status:</p><p><code>calicoctl ipam show --show-blocks</code></p><p>This displays the current IP allocations and blocks.</p><h2 id="h-important-considerations" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Important Considerations</h2><p><strong>Avoid IP Conflicts:</strong> Ensure that the CIDR of the new IP pool does not overlap with other networks in your cluster or external networks.<br><strong>Routing and Networking:</strong> If your cluster uses overlay networking (e.g., IP-in-IP, VXLAN), ensure that the new IP range is properly routed within your network infrastructure.<br><strong>Policy Enforcement:</strong> Update network policies if necessary to allow or restrict traffic to and from the new IP range.</p><h2 id="h-conclusion" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Conclusion</h2><p>By configuring an additional IP pool with a custom <code>blockSize</code> in Calico, you gain finer control over IP address allocation within your Kubernetes cluster&apos;s internal network. This setup can improve IP address utilization and prevent potential exhaustion.</p><p>Using <code>calicoctl apply -f ippool.yaml</code> ensures that configurations are validated before application, reducing the risk of misconfigurations impacting your cluster.</p><p>Note: Be sure to replace the CIDR range and other parameters in the examples with values appropriate for your network environment. Always test changes in a staging environment before applying them to production.</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[Кастодиальный поставщик ликвидности (платежный посредник). Cross-App Market Maker.]]></title>
            <link>https://paragraph.com/@defi-in-security/cross-app-market-maker</link>
            <guid>ebHbxHxlZsexp1AiHuYs</guid>
            <pubDate>Thu, 19 Sep 2024 18:04:27 GMT</pubDate>
            <description><![CDATA[This public proposal for improvement is released in order to celebrate TOKEN2049 Singapore event closing on 19 SEPTEMBER 2024 • MARINA BAY SANDS and promote alternative decentralized stablecoins. Это публичное предложение по улучшению публикуется для того, чтобы отпраздновать событие TOKEN2049 Singapore, закрывающееся 19 СЕНТЯБРЯ 2024 года • MARINA BAY SANDS, и продвинуть альтернативные децентрализованные стабилкоины. Кастодиальный поставщик ликвидности (платежный посредник) и межприложенческ...]]></description>
            <content:encoded><![CDATA[<p><code>This public proposal for improvement is released in order to celebrate TOKEN2049 Singapore event closing on 19 SEPTEMBER 2024 • MARINA BAY SANDS and promote alternative decentralized stablecoins.</code></p><p><code>Это публичное предложение по улучшению публикуется для того, чтобы отпраздновать событие TOKEN2049 Singapore, закрывающееся 19 СЕНТЯБРЯ 2024 года • MARINA BAY SANDS, и продвинуть альтернативные децентрализованные стабилкоины.</code></p><p><strong>Кастодиальный поставщик ликвидности (платежный посредник) и межприложенческий маркетмейкер.</strong></p><p>Cross-App Market Maker.</p><p><strong>Цель проекта</strong> — интеграция стейблкоина в максимальное количество приложений сети, где осуществляются платежи в цифровых валютах. Проект реализуется через следующие услуги:</p><ol><li><p>Техническая помощь в интеграции и поддержка эксплуатации.</p></li><li><p>Кастодиальный кошелек и мост для вывода средств в другие сети: P2P-рынок и/или предоставление ликвидности.</p></li></ol><p><strong>Основные направления:</strong></p><p><strong>а)</strong> Разработка SDK, виджетов, API и других инструментов для упрощенной интеграции платежной системы в различные приложения. В качестве примера для быстрого старта создается набор инструментов для лёгкой интеграции в Telegram-боты любого типа.</p><p><strong>б)</strong> Полное техническое сопровождение интеграции платежей с использованием данного токена в любое приложение. Это включает бесплатные доработки приложения для обеспечения работы с токеном и техническую поддержку на всех этапах.</p><p><strong>в)</strong> Кастодиальный кошелек (сначала в Telegram во встроенном магазине приложений) и мост для перевода активов в другие сети с минимальной ликвидностью. Также возможен P2P-обмен для вывода в фиатные валюты с первичной ликвидностью или заключение договоров с P2P-торговцами.</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[Proxies in DevOps routines]]></title>
            <link>https://paragraph.com/@defi-in-security/proxies-in-devops-routines</link>
            <guid>wmdIU13eNdfELGAJZ2jV</guid>
            <pubDate>Mon, 22 Jul 2024 19:59:05 GMT</pubDate>
            <description><![CDATA[Due to the Balkanisation of the Internet, modern IT specialists have to use various tools to access all the features available on the global network. One major tool is a proxy. Today, we will discuss proxies using the Linux CLI with DevOps applications as examples. We also raise concerns about the security of the process. 1. Configure Ubuntu VPS to Use Proxies for All CLI Tools that Support Proxy. 2. AWS CLI, Helm and Terraform and Proxies. 3. Traffic Security when Using Proxy. 4. Trust and V...]]></description>
            <content:encoded><![CDATA[<blockquote><p><strong>Due to </strong><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://script-ed.org/article/data-localisation-and-the-balkanisation-of-the-internet/"><strong>the Balkanisation of the Internet</strong></a><strong>, modern IT specialists have to use various tools to access all the features available on the global network. One major tool is a proxy. Today, we will discuss proxies using the Linux CLI with DevOps applications as examples. We also raise concerns about the security of the process.</strong></p><p><em>1. Configure Ubuntu VPS to Use Proxies for All CLI Tools that Support Proxy.<br>2. AWS CLI, Helm and Terraform and Proxies.<br>3. Traffic Security when Using Proxy.<br>4. Trust and Verification of the Proxy Server.<br>5. Using Proxy Chains</em></p></blockquote><h2 id="h-1-configure-ubuntu-vps-to-use-proxies-for-all-cli-tools-that-support-proxy" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">1. Configure Ubuntu VPS to Use Proxies for All CLI Tools that Support Proxy.</h2><p>To configure an Ubuntu VPS to use an external HTTPS or SOCKS5 proxy with authentication for all outgoing connections, you&apos;ll need to set up the environment variables for system-wide proxy settings. Here are detailed steps for both HTTPS and SOCKS5 proxies:</p><h3 id="h-1-configuring-an-https-proxy" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">1. Configuring an HTTPS Proxy</h3><h4 id="h-step-1-install-curl-and-wget" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Step 1: Install <code>curl</code> and <code>wget</code></h4><p>Ensure <code>curl</code> and <code>wget</code> are installed to verify the proxy settings.</p><pre data-type="codeBlock" text="sudo apt update
sudo apt install curl wget
"><code>sudo apt <span class="hljs-keyword">update</span>
sudo apt install curl wget
</code></pre><h4 id="h-step-2-set-environment-variables" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Step 2: Set Environment Variables</h4><p>Set the environment variables for the HTTP and HTTPS proxies. This includes the proxy server address, port, and authentication credentials.</p><p>Add the following lines to <code>/etc/environment</code>:</p><pre data-type="codeBlock" text="http_proxy=&quot;http://username:password@proxy_server:proxy_port&quot;
https_proxy=&quot;http://username:password@proxy_server:proxy_port&quot;
"><code><span class="hljs-attr">http_proxy</span>=<span class="hljs-string">"http://username:password@proxy_server:proxy_port"</span>
<span class="hljs-attr">https_proxy</span>=<span class="hljs-string">"http://username:password@proxy_server:proxy_port"</span>
</code></pre><p>Replace <code>username</code>, <code>password</code>, <code>proxy_server</code>, and <code>proxy_port</code> with your actual proxy credentials and server details.</p><p>For example:</p><pre data-type="codeBlock" text="http_proxy=&quot;http://user:pass@proxy.example.com:8080&quot;
https_proxy=&quot;http://user:pass@proxy.example.com:8080&quot;
"><code><span class="hljs-attr">http_proxy</span>=<span class="hljs-string">"http://user:pass@proxy.example.com:8080"</span>
<span class="hljs-attr">https_proxy</span>=<span class="hljs-string">"http://user:pass@proxy.example.com:8080"</span>
</code></pre><p>After editing, reload the environment variables:</p><pre data-type="codeBlock" text="source /etc/environment
"><code><span class="hljs-built_in">source</span> /etc/environment
</code></pre><h4 id="h-step-3-verify-the-configuration" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Step 3: Verify the Configuration</h4><p>Verify the proxy configuration using <code>curl</code> or <code>wget</code>:</p><pre data-type="codeBlock" text="curl -I http://example.com
wget -S http://example.com
"><code>curl <span class="hljs-operator">-</span>I http:<span class="hljs-comment">//example.com</span>
wget <span class="hljs-operator">-</span>S http:<span class="hljs-comment">//example.com</span>
</code></pre><h3 id="h-2-configuring-a-socks5-proxy" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">2. Configuring a SOCKS5 Proxy</h3><h4 id="h-step-1-install-tsocks-or-proxychains" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Step 1: Install <code>tsocks</code> or <code>proxychains</code></h4><p>Choose one of the utilities to route your traffic through a SOCKS5 proxy.</p><h5 id="h-using-tsocks" class="text-lg font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Using <code>tsocks</code></h5><p>Install <code>tsocks</code>:</p><pre data-type="codeBlock" text="sudo apt install tsocks
"><code></code></pre><p>Edit the <code>tsocks</code> configuration file located at <code>/etc/tsocks.conf</code>:</p><pre data-type="codeBlock" text="sudo nano /etc/tsocks.conf
"><code>sudo nano <span class="hljs-operator">/</span>etc<span class="hljs-operator">/</span>tsocks.conf
</code></pre><p>Add the following configuration, replacing <code>proxy_server</code>, <code>proxy_port</code>, <code>username</code>, and <code>password</code> with your actual proxy credentials and server details:</p><pre data-type="codeBlock" text="server = proxy_server
server_port = proxy_port
server_type = 5
default_user = username
default_pass = password
"><code><span class="hljs-attr">server</span> = proxy_server
<span class="hljs-attr">server_port</span> = proxy_port
<span class="hljs-attr">server_type</span> = <span class="hljs-number">5</span>
<span class="hljs-attr">default_user</span> = username
<span class="hljs-attr">default_pass</span> = password
</code></pre><h5 id="h-using-proxychains" class="text-lg font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Using <code>proxychains</code></h5><p>Install <code>proxychains</code>:</p><pre data-type="codeBlock" text="sudo apt install proxychains
"><code></code></pre><p>Edit the <code>proxychains</code> configuration file located at <code>/etc/proxychains.conf</code>:</p><pre data-type="codeBlock" text="sudo nano /etc/proxychains.conf
"><code>sudo nano <span class="hljs-operator">/</span>etc<span class="hljs-operator">/</span>proxychains.conf
</code></pre><p>Add the following line at the end of the configuration file, replacing <code>proxy_server</code>, <code>proxy_port</code>, <code>username</code>, and <code>password</code> with your actual proxy credentials and server details:</p><pre data-type="codeBlock" text="socks5 username:password@proxy_server proxy_port
"><code>socks5 <span class="hljs-symbol">username</span><span class="hljs-punctuation">:</span>password<span class="hljs-meta">@proxy_server</span> proxy_port
</code></pre><h4 id="h-step-2-configure-environment-variables-for-system-wide-proxy-optional" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Step 2: Configure Environment Variables for System-Wide Proxy (Optional)</h4><p>To apply the proxy settings system-wide, you may need to wrap your commands with <code>tsocks</code> or <code>proxychains</code>:</p><pre data-type="codeBlock" text="tsocks curl -I http://example.com
proxychains curl -I http://example.com
"><code>tsocks curl <span class="hljs-operator">-</span>I http:<span class="hljs-comment">//example.com</span>
proxychains curl <span class="hljs-operator">-</span>I http:<span class="hljs-comment">//example.com</span>
</code></pre><p>To use the proxy for all outgoing connections, create aliases for frequently used commands:</p><p>Add the following lines to your shell configuration file (e.g., <code>.bashrc</code>, <code>.zshrc</code>):</p><pre data-type="codeBlock" text="alias curl=&apos;tsocks curl&apos;
alias wget=&apos;tsocks wget&apos;
"><code>alias <span class="hljs-attr">curl</span>=<span class="hljs-string">'tsocks curl'</span>
alias <span class="hljs-attr">wget</span>=<span class="hljs-string">'tsocks wget'</span>
</code></pre><p>Or for <code>proxychains</code>:</p><pre data-type="codeBlock" text="alias curl=&apos;proxychains curl&apos;
alias wget=&apos;proxychains wget&apos;
"><code>alias <span class="hljs-attr">curl</span>=<span class="hljs-string">'proxychains curl'</span>
alias <span class="hljs-attr">wget</span>=<span class="hljs-string">'proxychains wget'</span>
</code></pre><p>After editing, reload your shell configuration:</p><pre data-type="codeBlock" text="source ~/.bashrc
"><code>source <span class="hljs-operator">~</span><span class="hljs-operator">/</span>.bashrc
</code></pre><h3 id="h-notes" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Notes:</h3><ul><li><p>When using environment variables for HTTPS proxies with authentication, your credentials will be exposed in process lists. For better security, consider using tools like <code>cntlm</code> for NTLM proxies or other secure methods for proxy authentication.</p></li><li><p>The above methods will route traffic through the proxy for all commands run in the terminal. For GUI applications, additional configuration may be needed.</p></li></ul><p>By following these steps, you can configure your Ubuntu VPS to use an external HTTPS or SOCKS5 proxy with authentication for all outgoing connections.</p><h2 id="h-2-aws-cli-helm-and-terraform-and-proxies" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">2. AWS CLI, Helm and Terraform and Proxies.</h2><p>Yes, <code>aws-cli</code>, <code>helm</code>, and <code>terraform</code> can be configured to use the proxy settings specified in the environment variables. Here&apos;s how you can ensure these tools use the proxy settings:</p><h3 id="h-1-configuring-environment-variables" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">1. Configuring Environment Variables</h3><p>Set the environment variables for HTTP and HTTPS proxies. You can add these lines to <code>/etc/environment</code> or your shell configuration file (<code>~/.bashrc</code>, <code>~/.zshrc</code>, etc.):</p><pre data-type="codeBlock" text="http_proxy=&quot;http://username:password@proxy_server:proxy_port&quot;
https_proxy=&quot;http://username:password@proxy_server:proxy_port&quot;
no_proxy=&quot;127.0.0.1,localhost&quot;
"><code><span class="hljs-attr">http_proxy</span>=<span class="hljs-string">"http://username:password@proxy_server:proxy_port"</span>
<span class="hljs-attr">https_proxy</span>=<span class="hljs-string">"http://username:password@proxy_server:proxy_port"</span>
<span class="hljs-attr">no_proxy</span>=<span class="hljs-string">"127.0.0.1,localhost"</span>
</code></pre><p>Replace <code>username</code>, <code>password</code>, <code>proxy_server</code>, and <code>proxy_port</code> with your actual proxy credentials and server details. The <code>no_proxy</code> variable can be adjusted based on your needs to bypass the proxy for local addresses.</p><p>After editing, reload the environment variables:</p><pre data-type="codeBlock" text="source /etc/environment
source ~/.bashrc  # or source ~/.zshrc
"><code>source <span class="hljs-operator">/</span>etc<span class="hljs-operator">/</span>environment
source <span class="hljs-operator">~</span><span class="hljs-operator">/</span>.bashrc  # or source <span class="hljs-operator">~</span><span class="hljs-operator">/</span>.zshrc
</code></pre><h3 id="h-2-aws-cli" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">2. AWS CLI</h3><p>The AWS CLI will automatically use the proxy settings specified in the <code>http_proxy</code> and <code>https_proxy</code> environment variables.</p><p>To verify, you can run a simple AWS CLI command:</p><pre data-type="codeBlock" text="aws s3 ls
"><code>aws s3 <span class="hljs-built_in">ls</span>
</code></pre><p>If configured correctly, the AWS CLI will use the proxy settings for this command.</p><h3 id="h-3-helm" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">3. Helm</h3><p>Helm also respects the <code>http_proxy</code> and <code>https_proxy</code> environment variables. You can verify by running a Helm command:</p><pre data-type="codeBlock" text="helm repo update
"><code>helm repo <span class="hljs-keyword">update</span>
</code></pre><p>If Helm uses the proxy, it should update the repositories without issues.</p><h3 id="h-4-terraform" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">4. Terraform</h3><p>Terraform will use the <code>http_proxy</code> and <code>https_proxy</code> environment variables for outgoing HTTP and HTTPS connections. To verify, run a Terraform command such as:</p><pre data-type="codeBlock" text="terraform init
"><code>terraform <span class="hljs-keyword">init</span>
</code></pre><p>If the initialization process completes successfully, Terraform is using the proxy settings.</p><h3 id="h-5-verifying-proxy-configuration" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">5. Verifying Proxy Configuration</h3><p>To ensure all these tools are using the proxy, you can use a network monitoring tool like <code>tcpdump</code> or check the proxy server logs if you have access.</p><p>For example, using <code>tcpdump</code> to monitor traffic:</p><pre data-type="codeBlock" text="sudo tcpdump -i eth0 -nn host proxy_server
"><code>sudo tcpdump <span class="hljs-operator">-</span>i eth0 <span class="hljs-operator">-</span>nn host proxy_server
</code></pre><p>Replace <code>eth0</code> with your actual network interface and <code>proxy_server</code> with your proxy server&apos;s IP address. This will show you traffic going to and from the proxy server.</p><h3 id="h-additional-notes" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Additional Notes</h3><ol><li><p><strong>Security</strong>: Be cautious with storing plaintext proxy credentials in environment variables, especially on shared systems. Consider using more secure methods like encrypted configuration files or credential managers if possible.</p></li><li><p><strong>Tool-specific configurations</strong>: Some tools might have additional configurations for proxies, but generally, setting the environment variables as described will work for most command-line tools.</p></li></ol><p>By following these steps, <code>aws-cli</code>, <code>helm</code>, and <code>terraform</code> should all use the specified proxy settings from the environment variables.</p><h2 id="h-3-traffic-security-when-using-proxy" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">3. Traffic Security when Using Proxy.</h2><p>When using a proxy, the security of your traffic depends on the type of proxy and the configuration:</p><h3 id="h-https-proxy-with-authentication" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">HTTPS Proxy with Authentication</h3><p><strong>HTTPS proxies</strong> use TLS/SSL to secure the connection between your client (e.g., a web browser, command-line tool) and the proxy server. Here’s how the security works:</p><ol><li><p><strong>Connection Security</strong>: The connection between your client and the HTTPS proxy server is encrypted using TLS/SSL. This means that anyone intercepting the traffic between your client and the proxy server cannot easily read the data.</p></li><li><p><strong>Authentication Security</strong>: If the proxy requires authentication, the credentials (username and password) are sent over this encrypted connection, so they are protected from eavesdropping.</p></li><li><p><strong>End-to-End Encryption</strong>: After the HTTPS proxy server, the traffic is decrypted and then forwarded to the destination server. If the destination server uses HTTPS, then the traffic will be re-encrypted between the proxy server and the destination server, ensuring end-to-end encryption. If the destination server uses HTTP, the traffic will be unencrypted between the proxy server and the destination server.</p></li></ol><h3 id="h-socks5-proxy-with-authentication" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">SOCKS5 Proxy with Authentication</h3><p><strong>SOCKS5 proxies</strong> can operate at a lower level (the transport layer), and they can handle various types of traffic (not just HTTP/HTTPS). Here&apos;s how the security works:</p><ol><li><p><strong>Connection Security</strong>: SOCKS5 itself does not encrypt traffic. However, it can support a variety of authentication methods. If used with TLS (SOCKS5 over TLS), the connection can be encrypted, but this requires specific support and configuration on both the client and the proxy server.</p></li><li><p><strong>Authentication Security</strong>: If the SOCKS5 proxy uses username/password authentication, these credentials can be sent in plain text unless an additional encryption layer (like TLS) is used.</p></li><li><p><strong>End-to-End Encryption</strong>: For end-to-end encryption, the applications using the SOCKS5 proxy must use their own encryption (e.g., HTTPS). This ensures that traffic remains encrypted from the client to the destination, even if it passes through the SOCKS5 proxy unencrypted.</p></li></ol><h3 id="h-summary" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Summary</h3><ul><li><p><strong>HTTPS Proxy</strong>: Provides encryption between the client and the proxy server using TLS/SSL. Authentication credentials are secure, and if the final destination also uses HTTPS, end-to-end encryption is maintained.</p></li><li><p><strong>SOCKS5 Proxy</strong>: Does not provide inherent encryption. To secure traffic, it must be used in conjunction with an encryption protocol like TLS. Authentication credentials can be sent in plain text unless additional measures are taken.</p></li></ul><h3 id="h-ensuring-secure-traffic" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Ensuring Secure Traffic</h3><ol><li><p><strong>Use HTTPS for Sensitive Data</strong>: Always ensure that sensitive data is sent over HTTPS, regardless of the proxy type. This ensures end-to-end encryption.</p></li><li><p><strong>Verify Proxy Configuration</strong>: Ensure your proxy is properly configured to support TLS/SSL (for HTTPS proxies) or is used in conjunction with an encrypted protocol (for SOCKS5).</p></li><li><p><strong>Check Proxy Credentials</strong>: Ensure that your credentials are not exposed in plaintext by checking the proxy and client configurations.</p></li><li><p><strong>Monitor Traffic</strong>: Use tools like <code>tcpdump</code> or <code>Wireshark</code> to verify that your traffic is encrypted as expected.</p></li></ol><p>By following these guidelines, you can ensure that your traffic is secure when using HTTPS or SOCKS5 proxies.</p><h2 id="h-4-trust-and-verification-of-the-proxy-server" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">4. Trust and Verification of the Proxy Server.</h2><p>You may raise a valid point regarding the trust and verification of the proxy server itself. When using a proxy, especially one that requires authentication and handles sensitive data, it&apos;s crucial to ensure that the connection is secure and trusted. Here are steps to mitigate the risk of man-in-the-middle (MitM) attacks and ensure the proxy&apos;s authenticity:</p><h3 id="h-1-https-proxy-verification" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">1. HTTPS Proxy Verification</h3><p>When using an HTTPS proxy, you can leverage Public Key Infrastructure (PKI) to ensure the proxy server&apos;s identity. Here&apos;s how:</p><h4 id="h-step-1-certificate-verification" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Step 1: Certificate Verification</h4><p>Ensure that the HTTPS proxy server uses a valid SSL/TLS certificate issued by a trusted Certificate Authority (CA). You can verify this certificate on the client side.</p><ul><li><p>When connecting to the HTTPS proxy, your client should verify the server&apos;s certificate against trusted CAs.</p></li><li><p>If the proxy&apos;s certificate is invalid, expired, or self-signed, your client should reject the connection.</p></li></ul><h4 id="h-step-2-configure-ca-certificates" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Step 2: Configure CA Certificates</h4><p>On your Ubuntu VPS, you can configure the system to trust specific CAs or proxy certificates:</p><ul><li><p><strong>System-wide CA certificates</strong>:</p><ul><li><p>Place your trusted CA certificates in <code>/usr/local/share/ca-certificates/</code> and run <code>sudo update-ca-certificates</code>.</p></li></ul></li><li><p><strong>Application-specific CA certificates</strong>:</p><ul><li><p>For tools like <code>curl</code>, you can specify the CA bundle using the <code>--cacert</code> option.</p></li></ul></li></ul><p>Example for <code>curl</code>:</p><pre data-type="codeBlock" text="curl --cacert /path/to/ca-certificates.crt -x https://username:password@proxy_server:proxy_port https://example.com
"><code>curl <span class="hljs-operator">-</span><span class="hljs-operator">-</span>cacert <span class="hljs-operator">/</span>path<span class="hljs-operator">/</span>to<span class="hljs-operator">/</span>ca<span class="hljs-operator">-</span>certificates.crt <span class="hljs-operator">-</span>x https:<span class="hljs-comment">//username:password@proxy_server:proxy_port https://example.com</span>
</code></pre><h3 id="h-2-socks5-proxy-verification" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">2. SOCKS5 Proxy Verification</h3><p>SOCKS5 proxies do not inherently support TLS. However, you can ensure secure connections by combining SOCKS5 with TLS or SSH tunneling.</p><h4 id="h-step-1-use-socks5-over-tls" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Step 1: Use SOCKS5 over TLS</h4><p>If the SOCKS5 proxy supports TLS, you can configure your client to establish a TLS connection to the SOCKS5 proxy. This requires both the client and proxy to support this configuration.</p><h4 id="h-step-2-ssh-tunneling" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Step 2: SSH Tunneling</h4><p>Another common approach is to use SSH to create a secure tunnel and use it as a SOCKS5 proxy.</p><ol><li><p><strong>Set up SSH tunnel</strong>:</p><pre data-type="codeBlock" text="ssh -D 1080 -f -C -q -N user@proxy_server
"><code>ssh <span class="hljs-operator">-</span>D <span class="hljs-number">1080</span> <span class="hljs-operator">-</span>f <span class="hljs-operator">-</span>C <span class="hljs-operator">-</span>q <span class="hljs-operator">-</span>N user@proxy_server
</code></pre><ul><li><p><code>-D 1080</code>: Specifies the local SOCKS5 port.</p></li><li><p><code>-f</code>: Sends SSH to the background after authentication.</p></li><li><p><code>-C</code>: Enables compression.</p></li><li><p><code>-q</code>: Quiet mode.</p></li><li><p><code>-N</code>: Do not execute remote commands.</p></li></ul></li><li><p><strong>Configure applications to use the local SOCKS5 proxy</strong> (e.g., <code>localhost:1080</code>).</p></li></ol><h3 id="h-3-dns-over-https-doh-and-dns-over-tls-dot" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">3. DNS Over HTTPS (DoH) and DNS Over TLS (DoT)</h3><p>Ensure DNS queries are secure by using DNS over HTTPS (DoH) or DNS over TLS (DoT):</p><ul><li><p><strong>DoH</strong>: DNS queries are sent via HTTPS, securing them against eavesdropping and MitM attacks.</p></li><li><p><strong>DoT</strong>: DNS queries are encrypted using TLS.</p></li></ul><h3 id="h-4-additional-security-measures" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">4. Additional Security Measures</h3><h4 id="h-step-1-use-a-vpn" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Step 1: Use a VPN</h4><p>A VPN can encrypt all traffic between your client and the VPN server, ensuring that even if a MitM attack occurs on the proxy, the traffic remains encrypted.</p><h4 id="h-step-2-monitor-and-audit-connections" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Step 2: Monitor and Audit Connections</h4><p>Regularly monitor and audit your connections using tools like <code>tcpdump</code> or <code>Wireshark</code> to detect any anomalies or potential MitM attacks.</p><h4 id="h-step-3-use-trusted-proxies" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Step 3: Use Trusted Proxies</h4><p>Where possible, use proxies that you trust or those provided by reputable providers. Avoid using public proxies for sensitive data.</p><h3 id="h-conclusion" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Conclusion</h3><p>To ensure that your traffic to the proxy is secure and mitigate the risk of MitM attacks, you should:</p><ul><li><p>Verify the proxy server&apos;s certificate using PKI for HTTPS proxies.</p></li><li><p>Use secure tunneling methods like SSH for SOCKS5 proxies.</p></li><li><p>Utilize DNS over HTTPS or DNS over TLS to secure DNS queries.</p></li><li><p>Consider additional layers of security such as VPNs and regular monitoring.</p></li></ul><p>By implementing these measures, you can ensure the authenticity and security of your connections through proxies.</p><h2 id="h-5-using-proxy-chains" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">5. Using Proxy Chains.</h2><p>If you are not able to connect to your proxy directly you have to use chain of proxies. Configuring a chain of proxies directly through environment variables on a Linux system isn&apos;t natively supported by most tools. Typically, environment variables like <code>http_proxy</code>, <code>https_proxy</code>, and <code>no_proxy</code> only support single proxy configurations.</p><p>However, you can achieve proxy chaining using specialized tools or configurations. Here are a few methods:</p><h3 id="h-1-using-proxychains" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">1. Using <code>proxychains</code></h3><p><code>proxychains</code> is a versatile tool that allows you to chain multiple proxies together. It supports HTTP, SOCKS4, and SOCKS5 proxies.</p><h4 id="h-installation" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Installation</h4><pre data-type="codeBlock" text="sudo apt update
sudo apt install proxychains4
"><code>sudo apt <span class="hljs-keyword">update</span>
sudo apt install proxychains4
</code></pre><h4 id="h-configuration" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Configuration</h4><p>Edit the configuration file <code>/etc/proxychains4.conf</code>:</p><pre data-type="codeBlock" text="sudo nano /etc/proxychains4.conf
"><code>sudo nano <span class="hljs-operator">/</span>etc<span class="hljs-operator">/</span>proxychains4.conf
</code></pre><p>Add your proxy chain at the end of the file. For example:</p><pre data-type="codeBlock" text="# ProxyList format
#       type  host  port [user pass]
#       (socks4|socks5|http)  host  port [user pass]

[ProxyList]
http  proxy1.example.com 8080 user1 pass1
socks5  proxy2.example.com 1080 user2 pass2
http  proxy3.example.com 3128 user3 pass3
"><code># ProxyList format
#       <span class="hljs-keyword">type</span>  host  port [user pass]
#       (socks4<span class="hljs-operator">|</span>socks5<span class="hljs-operator">|</span>http)  host  port [user pass]

[ProxyList]
http  proxy1.example.com <span class="hljs-number">8080</span> user1 pass1
socks5  proxy2.example.com <span class="hljs-number">1080</span> user2 pass2
http  proxy3.example.com <span class="hljs-number">3128</span> user3 pass3
</code></pre><h4 id="h-usage" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Usage</h4><p>Run your command with <code>proxychains</code>:</p><pre data-type="codeBlock" text="proxychains4 curl http://example.com
proxychains4 wget http://example.com
proxychains4 aws s3 ls
proxychains4 helm repo update
proxychains4 terraform init
"><code>proxychains4 curl http://example.com
proxychains4 wget http://example.com
proxychains4 aws s3 <span class="hljs-built_in">ls</span>
proxychains4 helm repo update
proxychains4 terraform init
</code></pre><h3 id="h-2-using-tsocks" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">2. Using <code>tsocks</code></h3><p><code>tsocks</code> is another tool that can be used for SOCKS proxy chaining. It does not support HTTP proxies natively but can be combined with other tools.</p><h4 id="h-installation" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Installation</h4><pre data-type="codeBlock" text="sudo apt install tsocks
"><code></code></pre><h4 id="h-configuration" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Configuration</h4><p>Edit the configuration file <code>/etc/tsocks.conf</code>:</p><pre data-type="codeBlock" text="sudo nano /etc/tsocks.conf
"><code>sudo nano <span class="hljs-operator">/</span>etc<span class="hljs-operator">/</span>tsocks.conf
</code></pre><p>Add your proxy chain:</p><pre data-type="codeBlock" text="server = proxy1.example.com
server_type = 5
server_port = 1080

default_user = user1
default_pass = pass1

server = proxy2.example.com
server_type = 5
server_port = 1080

default_user = user2
default_pass = pass2
"><code><span class="hljs-attr">server</span> = proxy1.example.com
<span class="hljs-attr">server_type</span> = <span class="hljs-number">5</span>
<span class="hljs-attr">server_port</span> = <span class="hljs-number">1080</span>

<span class="hljs-attr">default_user</span> = user1
<span class="hljs-attr">default_pass</span> = pass1

<span class="hljs-attr">server</span> = proxy2.example.com
<span class="hljs-attr">server_type</span> = <span class="hljs-number">5</span>
<span class="hljs-attr">server_port</span> = <span class="hljs-number">1080</span>

<span class="hljs-attr">default_user</span> = user2
<span class="hljs-attr">default_pass</span> = pass2
</code></pre><h4 id="h-usage" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Usage</h4><p>Run your command with <code>tsocks</code>:</p><pre data-type="codeBlock" text="tsocks curl http://example.com
tsocks wget http://example.com
tsocks aws s3 ls
tsocks helm repo update
tsocks terraform init
"><code>tsocks curl http://example.com
tsocks wget http://example.com
tsocks aws s3 <span class="hljs-built_in">ls</span>
tsocks helm repo update
tsocks terraform init
</code></pre><h3 id="h-3-custom-scripts" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">3. Custom Scripts</h3><p>You can create custom scripts to handle proxy chaining for specific tools. For example, using <code>curl</code> with a chain of proxies:</p><pre data-type="codeBlock" text="#!/bin/bash

PROXY1=&quot;http://user1:pass1@proxy1.example.com:8080&quot;
PROXY2=&quot;http://user2:pass2@proxy2.example.com:8080&quot;
PROXY3=&quot;http://user3:pass3@proxy3.example.com:3128&quot;

URL=$1

curl -x $PROXY1 -x $PROXY2 -x $PROXY3 $URL
"><code><span class="hljs-meta">#!/bin/bash</span>

PROXY1=<span class="hljs-string">"http://user1:pass1@proxy1.example.com:8080"</span>
PROXY2=<span class="hljs-string">"http://user2:pass2@proxy2.example.com:8080"</span>
PROXY3=<span class="hljs-string">"http://user3:pass3@proxy3.example.com:3128"</span>

URL=<span class="hljs-variable">$1</span>

curl -x <span class="hljs-variable">$PROXY1</span> -x <span class="hljs-variable">$PROXY2</span> -x <span class="hljs-variable">$PROXY3</span> <span class="hljs-variable">$URL</span>
</code></pre><p>Save this script as <code>chaincurl.sh</code>, make it executable, and use it:</p><pre data-type="codeBlock" text="chmod +755 chaincurl.sh
./chaincurl.sh http://example.com
"><code>chmod <span class="hljs-operator">+</span><span class="hljs-number">755</span> chaincurl.sh
./chaincurl.sh http:<span class="hljs-comment">//example.com</span>
</code></pre><h3 id="h-4-chaining-proxies-in-web-browsers" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">4. Chaining Proxies in Web Browsers</h3><p>If you need proxy chaining in web browsers, tools like FoxyProxy can be used to configure multiple proxies.</p><h3 id="h-summary" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Summary</h3><p>To chain proxies and use them with Linux CLI tools:</p><ul><li><p>Use <code>proxychains</code> for versatile proxy chaining with support for HTTP, SOCKS4, and SOCKS5.</p></li><li><p>Use <code>tsocks</code> for SOCKS proxy chaining.</p></li><li><p>Create custom scripts for specific tools like <code>curl</code>.</p></li><li><p>Note that chaining proxies via environment variables alone is not directly supported.</p></li></ul><p>By using these methods, you can configure and utilize a chain of proxies for your Linux CLI tools effectively.</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[DOCKER SWARM FOR DUMMIES]]></title>
            <link>https://paragraph.com/@defi-in-security/docker-swarm-for-dummies</link>
            <guid>ZDeNH1hc5wRz6ltmT5V8</guid>
            <pubDate>Wed, 10 Jul 2024 01:43:31 GMT</pubDate>
            <description><![CDATA[Table of contents:0. Links for Additional Reading 1. Key Points About Docker Swarm Management and Monitoring 2. Docker Swarm in Container Orchestration: Between Docker Compose and Kubernetes 3. Advanced Features of Docker Swarm for DevOps 4. Rolling Updates, Rollbacks, and Resilience in Docker Swarm 5. Deploying Stateful Applications in Docker Swarm 6. Context of Labels in Docker Swarm 7. Load Balancing in Docker Swarm 8. Portainer on Docker Swarm 9. Portainer vs Swarmpit 10. Portainer Interf...]]></description>
            <content:encoded><![CDATA[<h2 id="h-table-of-contents" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Table of contents:</h2><blockquote><p><em>0. Links for Additional Reading<br>1. Key Points About Docker Swarm Management and Monitoring<br>2. Docker Swarm in Container Orchestration: Between Docker Compose and Kubernetes<br>3. Advanced Features of Docker Swarm for DevOps<br>4. Rolling Updates, Rollbacks, and Resilience in Docker Swarm<br>5. Deploying Stateful Applications in Docker Swarm<br>6. Context of Labels in Docker Swarm<br>7. Load Balancing in Docker Swarm<br>8. Portainer on Docker Swarm<br>9. Portainer vs Swarmpit</em><br>10. Portainer Interface<br>11. Configs in Portainer</p></blockquote><h2 id="h-0-links-for-additional-reading" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">0. Links for additional reading</h2><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/BretFisher/awesome-swarm">https://github.com/BretFisher/awesome-swarm</a></p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://docs.docker.com/engine/swarm/ingress/">https://docs.docker.com/engine/swarm/ingress/</a></p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://blog.okami101.io/2022/02/setup-a-docker-swarm-cluster-part-v-monitoring/">https://blog.okami101.io/2022/02/setup-a-docker-swarm-cluster-part-v-monitoring/</a></p><h2 id="h-1-key-points-about-docker-swarm-management-and-monitoring" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">1. Key Points About Docker Swarm Management and Monitoring</h2><h3 id="h-docker-cli" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Docker CLI</h3><p>The primary way to manage and monitor Docker Swarm is through the Docker Command Line Interface (CLI). Some of the important commands include:</p><ul><li><p><code>docker swarm init</code>: Initialize a new Swarm.</p></li><li><p><code>docker node ls</code>: List all nodes in the Swarm.</p></li><li><p><code>docker service ls</code>: List all services running in the Swarm.</p></li><li><p><code>docker stack deploy</code>: Deploy a new stack of services.</p></li><li><p><code>docker service scale</code>: Scale a service to the desired number of replicas.</p></li></ul><h3 id="h-third-party-tools" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Third-Party Tools</h3><p>For a more user-friendly interface and enhanced monitoring capabilities, you can use third-party tools:</p><ul><li><p><strong>Portainer</strong>: A lightweight management UI which allows you to manage your Docker environments, including Swarm clusters. It provides a comprehensive GUI for managing containers, images, networks, and volumes.</p></li><li><p><strong>Swarmpit</strong>: Another management UI specifically designed for Docker Swarm, offering real-time monitoring, log access, and service management.</p></li></ul><h3 id="h-integration-with-monitoring-systems" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Integration with Monitoring Systems</h3><p>To achieve advanced monitoring and alerting, Docker Swarm can be integrated with various monitoring tools:</p><ul><li><p><strong>Prometheus and Grafana</strong>: Prometheus can scrape metrics from Docker Swarm nodes and services, and Grafana can visualize these metrics. There are exporters and configurations available to set up this integration.</p></li><li><p><strong>ELK Stack (Elasticsearch, Logstash, and Kibana)</strong>: For log aggregation and analysis, the ELK stack can be configured to collect and visualize logs from your Swarm cluster.</p></li><li><p><strong>Datadog, New Relic, and other APM tools</strong>: These tools can provide comprehensive monitoring and alerting capabilities for Docker Swarm clusters.</p></li></ul><h3 id="h-example-setup-with-prometheus-and-grafana" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Example Setup with Prometheus and Grafana</h3><p>To set up monitoring with Prometheus and Grafana for Docker Swarm, you can follow these steps:</p><ol><li><p><strong>Prometheus Configuration</strong>:</p><ul><li><p>Deploy Prometheus using a Docker service.</p></li><li><p>Configure Prometheus to scrape metrics from Docker Swarm nodes using a <code>prometheus.yml</code> configuration file.</p></li></ul><pre data-type="codeBlock" text="global:
  scrape_interval: 15s

scrape_configs:
  - job_name: &apos;docker&apos;
    static_configs:
      - targets: [&apos;&lt;node_ip&gt;:9323&apos;]
"><code><span class="hljs-attr">global:</span>
  <span class="hljs-attr">scrape_interval:</span> <span class="hljs-string">15s</span>

<span class="hljs-attr">scrape_configs:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">job_name:</span> <span class="hljs-string">'docker'</span>
    <span class="hljs-attr">static_configs:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">targets:</span> [<span class="hljs-string">'&#x3C;node_ip>:9323'</span>]
</code></pre><p>You need to run the <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/prometheus/node_exporter">Prometheus Docker Daemon Metrics Exporter</a> on each Swarm node to expose metrics on port 9323.</p></li><li><p><strong>Grafana Setup</strong>:</p><ul><li><p>Deploy Grafana as a Docker service.</p></li><li><p>Add Prometheus as a data source in Grafana.</p></li><li><p>Create dashboards to visualize metrics from Prometheus.</p></li></ul></li></ol><h3 id="h-conclusion" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Conclusion</h3><p>While Docker Swarm does not come with an official GUI dashboard, it can be effectively managed and monitored using the Docker CLI, third-party tools like Portainer and Swarmpit, and by integrating with comprehensive monitoring solutions such as Prometheus and Grafana.</p><h2 id="h-2-docker-swarm-in-container-orchestration-between-docker-compose-and-kubernetes" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">2. Docker Swarm in Container Orchestration: Between Docker Compose and Kubernetes</h2><h4 id="h-introduction" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Introduction</h4><p>Container orchestration is a critical aspect of modern software deployment and management, facilitating the automated deployment, scaling, and operation of application containers. The three predominant tools in this domain are Docker Compose, Docker Swarm, and Kubernetes. While Docker Compose is primarily for single-host deployments, Docker Swarm and Kubernetes cater to multi-host orchestration. This article delves into Docker Swarm&apos;s position within the container orchestration ecosystem, highlighting its role between Docker Compose and Kubernetes, and elucidating the key technical differences.</p><h4 id="h-docker-compose-simplicity-for-single-host-deployments" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Docker Compose: Simplicity for Single-Host Deployments</h4><p>Docker Compose is a tool for defining and running multi-container Docker applications. It utilizes a YAML file to configure application services, networks, and volumes, providing a straightforward method to manage containers on a single Docker host.</p><p><strong>Key Features:</strong></p><ol><li><p><strong>Single-Host Focus:</strong> Designed for local development and testing environments.</p></li><li><p><strong>Ease of Use:</strong> Simplified syntax in a <code>docker-compose.yml</code> file.</p></li><li><p><strong>Limited Scalability:</strong> Not suitable for production-level scalability or multi-host environments.</p></li><li><p><strong>Basic Networking:</strong> Default bridge network, with simple service-to-service communication.</p></li></ol><p><strong>Example</strong> <code>docker-compose.yml</code>:</p><pre data-type="codeBlock" text="version: &apos;3&apos;
services:
  web:
    image: nginx
    ports:
      - &quot;80:80&quot;
  db:
    image: postgres
"><code><span class="hljs-attr">version:</span> <span class="hljs-string">'3'</span>
<span class="hljs-attr">services:</span>
  <span class="hljs-attr">web:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">nginx</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">"80:80"</span>
  <span class="hljs-attr">db:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">postgres</span>
</code></pre><h4 id="h-docker-swarm-bridging-the-gap" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Docker Swarm: Bridging the Gap</h4><p>Docker Swarm extends Docker&apos;s capabilities to support multi-host networking and orchestration, providing a simple yet powerful solution for scaling and managing containerized applications across a cluster of Docker hosts.</p><p><strong>Key Features:</strong></p><ol><li><p><strong>Native Docker Integration:</strong> Seamlessly integrates with Docker CLI and API.</p></li><li><p><strong>Declarative Service Model:</strong> Uses a declarative syntax for defining services and their desired state.</p></li><li><p><strong>Built-in Load Balancing:</strong> Automatically distributes network traffic among containers.</p></li><li><p><strong>Overlay Networking:</strong> Supports multi-host networking with secure, encrypted communications.</p></li><li><p><strong>Service Discovery:</strong> Integrated with Docker&apos;s DNS-based service discovery.</p></li></ol><p><strong>Swarm Mode Components:</strong></p><ul><li><p><strong>Manager Nodes:</strong> Handle the cluster&apos;s management and orchestration.</p></li><li><p><strong>Worker Nodes:</strong> Execute tasks assigned by managers.</p></li><li><p><strong>Services:</strong> Define how containers should be run, including image, replicas, and networking.</p></li><li><p><strong>Tasks:</strong> Atomic units of work assigned to worker nodes.</p></li></ul><p><strong>Example</strong> <code>docker-compose.yml</code> for Swarm:</p><pre data-type="codeBlock" text="version: &apos;3.8&apos;
services:
  web:
    image: nginx
    deploy:
      replicas: 3
      resources:
        limits:
          cpus: &quot;0.1&quot;
          memory: 50M
      restart_policy:
        condition: on-failure
    networks:
      - webnet
  db:
    image: postgres
    networks:
      - webnet

networks:
  webnet:
    driver: overlay
"><code><span class="hljs-attr">version:</span> <span class="hljs-string">'3.8'</span>
<span class="hljs-attr">services:</span>
  <span class="hljs-attr">web:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">nginx</span>
    <span class="hljs-attr">deploy:</span>
      <span class="hljs-attr">replicas:</span> <span class="hljs-number">3</span>
      <span class="hljs-attr">resources:</span>
        <span class="hljs-attr">limits:</span>
          <span class="hljs-attr">cpus:</span> <span class="hljs-string">"0.1"</span>
          <span class="hljs-attr">memory:</span> <span class="hljs-string">50M</span>
      <span class="hljs-attr">restart_policy:</span>
        <span class="hljs-attr">condition:</span> <span class="hljs-string">on-failure</span>
    <span class="hljs-attr">networks:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">webnet</span>
  <span class="hljs-attr">db:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">postgres</span>
    <span class="hljs-attr">networks:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">webnet</span>

<span class="hljs-attr">networks:</span>
  <span class="hljs-attr">webnet:</span>
    <span class="hljs-attr">driver:</span> <span class="hljs-string">overlay</span>
</code></pre><p><strong>Key Technical Differences from Docker Compose:</strong></p><ol><li><p><strong>Cluster Management:</strong> Swarm mode manages a cluster of Docker nodes.</p></li><li><p><strong>Service Definitions:</strong> Enhanced service deployment configurations including resource constraints and restart policies.</p></li><li><p><strong>Scaling and Rollback:</strong> Native support for scaling services and rolling back updates.</p></li><li><p><strong>Network Security:</strong> Encrypted overlay networks for secure communication across nodes.</p></li></ol><h4 id="h-kubernetes-advanced-orchestration" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Kubernetes: Advanced Orchestration</h4><p>Kubernetes is an open-source container orchestration platform designed to automate the deployment, scaling, and management of containerized applications. It offers a rich set of features for complex, large-scale deployments.</p><p><strong>Key Features:</strong></p><ol><li><p><strong>Rich API:</strong> Extensive and highly customizable API.</p></li><li><p><strong>Pod Abstraction:</strong> Groups of containers that share storage, network, and lifecycle.</p></li><li><p><strong>Auto-scaling:</strong> Horizontal Pod Autoscaler for automatic scaling based on metrics.</p></li><li><p><strong>Service Mesh Integration:</strong> Advanced networking with tools like Istio for traffic management.</p></li><li><p><strong>Persistent Storage:</strong> Integration with various storage backends for stateful applications.</p></li><li><p><strong>Namespaces and RBAC:</strong> Fine-grained control over resource access and isolation.</p></li></ol><p><strong>Kubernetes Architecture:</strong></p><ul><li><p><strong>Master Node:</strong> Manages the cluster, running the API server, scheduler, and controller manager.</p></li><li><p><strong>Worker Nodes:</strong> Run containerized applications, managed by Kubelet and kube-proxy.</p></li><li><p><strong>Pods:</strong> The smallest deployable units in Kubernetes.</p></li><li><p><strong>Services:</strong> Abstractions that define logical sets of Pods and enable external access.</p></li></ul><p><strong>Example</strong> <code>deployment.yaml</code> in Kubernetes:</p><pre data-type="codeBlock" text="apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80
"><code><span class="hljs-attr">apiVersion:</span> <span class="hljs-string">apps/v1</span>
<span class="hljs-attr">kind:</span> <span class="hljs-string">Deployment</span>
<span class="hljs-attr">metadata:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">nginx-deployment</span>
<span class="hljs-attr">spec:</span>
  <span class="hljs-attr">replicas:</span> <span class="hljs-number">3</span>
  <span class="hljs-attr">selector:</span>
    <span class="hljs-attr">matchLabels:</span>
      <span class="hljs-attr">app:</span> <span class="hljs-string">nginx</span>
  <span class="hljs-attr">template:</span>
    <span class="hljs-attr">metadata:</span>
      <span class="hljs-attr">labels:</span>
        <span class="hljs-attr">app:</span> <span class="hljs-string">nginx</span>
    <span class="hljs-attr">spec:</span>
      <span class="hljs-attr">containers:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">nginx</span>
        <span class="hljs-attr">image:</span> <span class="hljs-string">nginx:1.14.2</span>
        <span class="hljs-attr">ports:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">containerPort:</span> <span class="hljs-number">80</span>
</code></pre><p><strong>Key Technical Differences from Docker Swarm:</strong></p><ol><li><p><strong>Complexity and Learning Curve:</strong> Kubernetes offers more advanced features at the cost of higher complexity and a steeper learning curve.</p></li><li><p><strong>Ecosystem and Extensibility:</strong> Extensive ecosystem with plugins, extensions, and integrations.</p></li><li><p><strong>Pod Concept:</strong> Groups multiple containers, allowing more complex application architectures.</p></li><li><p><strong>State Management:</strong> Built-in mechanisms for stateful applications and persistent storage.</p></li></ol><h4 id="h-conclusion" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Conclusion</h4><p>Docker Swarm serves as a middle ground in the container orchestration landscape. It provides a native, straightforward approach to multi-host orchestration, seamlessly extending Docker&apos;s capabilities beyond single-host deployments facilitated by Docker Compose. While not as feature-rich or complex as Kubernetes, Docker Swarm offers a balance of simplicity and functionality, making it suitable for medium-scale deployments and teams looking to leverage existing Docker expertise without the overhead of managing a Kubernetes cluster. For scenarios requiring advanced orchestration features, Kubernetes stands out as the most robust and scalable solution, albeit with a significant investment in learning and infrastructure.</p><h2 id="h-3-advanced-features-of-docker-swarm-for-devops" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">3. Advanced Features of Docker Swarm for DevOps</h2><p>Docker Swarm is a powerful container orchestration tool that extends Docker’s capabilities to manage clusters of hosts, providing a robust platform for deploying, managing, and scaling containerized applications. This article delves into some of Docker Swarm&apos;s advanced features, including overlay networking, load balancing, automated scaling, role-based access control (RBAC), and health checks, which are essential for building resilient, scalable, and secure applications.</p><h4 id="h-overlay-networking" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Overlay Networking</h4><p>Overlay networking in Docker Swarm enables containers running on different Docker hosts to communicate securely. This feature abstracts the underlying network infrastructure, providing a unified network interface for all containers in the Swarm.</p><p><strong>Key Technical Details:</strong></p><ul><li><p><strong>Network Driver:</strong> Uses the <code>overlay</code> network driver to create a virtual network that spans multiple Docker hosts.</p></li><li><p><strong>VXLAN:</strong> Utilizes VXLAN (Virtual Extensible LAN) for encapsulating Layer 2 Ethernet frames within Layer 3 IP packets, allowing for seamless container communication across different hosts.</p></li><li><p><strong>Encrypted Networks:</strong> Supports encryption for overlay networks, ensuring secure data transmission between containers on different nodes. Encryption is enabled by setting the <code>encrypted</code> flag in the network configuration.</p></li></ul><p><strong>Example: Creating an Encrypted Overlay Network</strong></p><pre data-type="codeBlock" text="docker network create --driver overlay --opt encrypted my_overlay_network
"><code>docker network create <span class="hljs-operator">-</span><span class="hljs-operator">-</span>driver overlay <span class="hljs-operator">-</span><span class="hljs-operator">-</span>opt encrypted my_overlay_network
</code></pre><p><strong>Benefits:</strong></p><ul><li><p><strong>Scalability:</strong> Facilitates the creation of large-scale, distributed applications.</p></li><li><p><strong>Security:</strong> Protects data in transit between containers.</p></li><li><p><strong>Simplicity:</strong> Abstracts the complexities of multi-host networking.</p></li></ul><h4 id="h-load-balancing" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Load Balancing</h4><p>Docker Swarm includes built-in load balancing to distribute network traffic across multiple container instances of a service, ensuring efficient utilization of resources and high availability.</p><p><strong>Key Technical Details:</strong></p><ul><li><p><strong>Routing Mesh:</strong> Swarm’s routing mesh allows any node in the Swarm to accept incoming requests and route them to the appropriate service task.</p></li><li><p><strong>Internal Load Balancing:</strong> Distributes traffic among service replicas using round-robin or other algorithms.</p></li><li><p><strong>DNS-Based Service Discovery:</strong> Automatically assigns a DNS name to each service, enabling containers to discover and connect to other services by name.</p></li></ul><p><strong>Example: Exposing a Service with Load Balancing</strong></p><pre data-type="codeBlock" text="docker service create --name my_web --replicas 3 --publish published=80,target=80 my_web_image
"><code>docker service create <span class="hljs-operator">-</span><span class="hljs-operator">-</span>name my_web <span class="hljs-operator">-</span><span class="hljs-operator">-</span>replicas <span class="hljs-number">3</span> <span class="hljs-operator">-</span><span class="hljs-operator">-</span>publish published<span class="hljs-operator">=</span><span class="hljs-number">80</span>,target<span class="hljs-operator">=</span><span class="hljs-number">80</span> my_web_image
</code></pre><p><strong>Benefits:</strong></p><ul><li><p><strong>High Availability:</strong> Ensures that application requests are evenly distributed and handled by available replicas.</p></li><li><p><strong>Fault Tolerance:</strong> Automatically reroutes traffic if a container instance fails.</p></li><li><p><strong>Simplified Networking:</strong> Abstracts the complexities of manual load balancer configuration.</p></li></ul><h4 id="h-automated-scaling" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Automated Scaling</h4><p>Automated scaling in Docker Swarm allows services to dynamically adjust the number of running containers based on current demand, ensuring optimal resource utilization.</p><p><strong>Key Technical Details:</strong></p><ul><li><p><strong>Declarative Service Model:</strong> Define the desired state of services, including the number of replicas, using a declarative approach.</p></li><li><p><strong>Scaling Commands:</strong> Easily scale services up or down using Docker CLI commands.</p></li><li><p><strong>Event-Driven Scaling:</strong> While Swarm does not natively support event-driven scaling, it can be integrated with external monitoring and scaling tools to achieve this functionality.</p></li></ul><p><strong>Example: Scaling a Service</strong></p><pre data-type="codeBlock" text="docker service scale my_web=5
"><code>docker service scale <span class="hljs-attr">my_web</span>=<span class="hljs-number">5</span>
</code></pre><p><strong>Benefits:</strong></p><ul><li><p><strong>Resource Optimization:</strong> Adjusts the number of containers to match workload demands, optimizing resource usage.</p></li><li><p><strong>Flexibility:</strong> Easily scale services as needed with simple commands.</p></li><li><p><strong>Cost Efficiency:</strong> Helps in managing costs by scaling down during low demand periods.</p></li></ul><h4 id="h-role-based-access-control-rbac" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Role-Based Access Control (RBAC)</h4><p>Docker Swarm provides role-based access control (RBAC) to secure the Swarm environment by defining permissions for different users, ensuring that only authorized personnel can perform specific actions.</p><p><strong>Key Technical Details:</strong></p><ul><li><p><strong>Swarm Roles:</strong> Includes predefined roles such as <code>admin</code> and <code>user</code>, each with specific permissions.</p></li><li><p><strong>Granular Permissions:</strong> Allows fine-grained control over who can access and manage nodes, services, and other resources in the Swarm.</p></li><li><p><strong>Certificate-Based Authentication:</strong> Uses mutual TLS for secure node communication and role assignment.</p></li></ul><p><strong>Example: Creating a User with Limited Permissions</strong> As of now, Swarm&apos;s RBAC is somewhat limited compared to Kubernetes, and most management is done through TLS certificates and managing Docker users with different permission sets.</p><p><strong>Benefits:</strong></p><ul><li><p><strong>Security:</strong> Ensures that sensitive operations are restricted to authorized users.</p></li><li><p><strong>Compliance:</strong> Helps in meeting regulatory requirements by enforcing access control policies.</p></li><li><p><strong>Auditability:</strong> Provides a clear audit trail of who performed what actions in the cluster.</p></li></ul><h4 id="h-health-checks-also-in-docker-compose" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Health Checks (also in Docker Compose)</h4><p>Health checks in Docker Swarm are used to monitor the status of containers, ensuring that only healthy containers receive traffic.</p><p><strong>Key Technical Details:</strong></p><ul><li><p><strong>Dockerfile Configuration:</strong> Define health checks in the Dockerfile using the <code>HEALTHCHECK</code> instruction.</p></li><li><p><strong>Service Health Checks:</strong> Swarm periodically executes the specified health check command and updates the container’s status based on the results.</p></li><li><p><strong>Health States:</strong> Containers can be in one of three states: starting, healthy, or unhealthy.</p></li></ul><p><strong>Example: Defining a Health Check in a Dockerfile</strong></p><pre data-type="codeBlock" text="HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
  CMD curl -f http://localhost/ || exit 1
"><code>HEALTHCHECK <span class="hljs-operator">-</span><span class="hljs-operator">-</span>interval<span class="hljs-operator">=</span>30s <span class="hljs-operator">-</span><span class="hljs-operator">-</span>timeout<span class="hljs-operator">=</span>10s <span class="hljs-operator">-</span><span class="hljs-operator">-</span>retries<span class="hljs-operator">=</span><span class="hljs-number">3</span> \
  CMD curl <span class="hljs-operator">-</span>f http:<span class="hljs-comment">//localhost/ || exit 1</span>
</code></pre><p><strong>Benefits:</strong></p><ul><li><p><strong>Reliability:</strong> Ensures that only healthy containers handle requests, improving application reliability.</p></li><li><p><strong>Automated Recovery:</strong> Swarm can automatically restart or replace unhealthy containers.</p></li><li><p><strong>Proactive Monitoring:</strong> Helps in identifying and addressing issues before they impact the end users.</p></li></ul><h3 id="h-conclusion" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Conclusion</h3><p>Docker Swarm&apos;s advanced features, including overlay networking, load balancing, automated scaling, RBAC, and health checks, provide a robust platform for managing containerized applications at scale. By leveraging these capabilities, DevOps engineers can build resilient, scalable, and secure infrastructures, ensuring optimal performance and high availability of their applications. Understanding and effectively utilizing these features are crucial for maintaining a modern, efficient, and secure DevOps environment.</p><h2 id="h-4-rolling-updates-rollbacks-and-resilience-in-docker-swarm" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">4. Rolling Updates, Rollbacks, and Resilience in Docker Swarm</h2><p>… which are essential features for maintaining service availability and reliability in a Docker Swarm cluster.</p><h3 id="h-rolling-updates" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Rolling Updates</h3><h4 id="h-overview" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Overview</h4><p>Rolling updates allow you to update services in a Docker Swarm incrementally, ensuring that there&apos;s minimal downtime and service disruption. This process involves updating a subset of replicas at a time rather than updating all instances simultaneously.</p><h4 id="h-how-it-works" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">How It Works</h4><ul><li><p><strong>Step-by-Step Process</strong>: Docker Swarm updates a specified number of service replicas at a time, waits for the updated replicas to become healthy, and then proceeds to update the next batch.</p></li><li><p><strong>Controlled Rollout</strong>: You can control the speed and scale of the update using parameters like <code>update-parallelism</code> and <code>delay</code>.</p></li><li><p><strong>Health Checks</strong>: Swarm uses health checks to ensure that the updated replicas are running correctly before proceeding with further updates.</p></li></ul><h4 id="h-example-configuration" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Example Configuration</h4><p>Here&apos;s how you might configure a rolling update in a <code>docker-compose.yml</code> file:</p><pre data-type="codeBlock" text="version: &apos;3.7&apos;

services:
  web:
    image: my-web-app:latest
    deploy:
      replicas: 5
      update_config:
        parallelism: 2
        delay: 10s
        failure_action: rollback
      restart_policy:
        condition: on-failure
"><code><span class="hljs-attr">version:</span> <span class="hljs-string">'3.7'</span>

<span class="hljs-attr">services:</span>
  <span class="hljs-attr">web:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">my-web-app:latest</span>
    <span class="hljs-attr">deploy:</span>
      <span class="hljs-attr">replicas:</span> <span class="hljs-number">5</span>
      <span class="hljs-attr">update_config:</span>
        <span class="hljs-attr">parallelism:</span> <span class="hljs-number">2</span>
        <span class="hljs-attr">delay:</span> <span class="hljs-string">10s</span>
        <span class="hljs-attr">failure_action:</span> <span class="hljs-string">rollback</span>
      <span class="hljs-attr">restart_policy:</span>
        <span class="hljs-attr">condition:</span> <span class="hljs-string">on-failure</span>
</code></pre><ul><li><p><code>parallelism: 2</code>: Updates two replicas at a time.</p></li><li><p><code>delay: 10s</code>: Waits 10 seconds between batches.</p></li><li><p><code>failure_action: rollback</code>: Rolls back to the previous version if the update fails.</p></li></ul><h3 id="h-rollbacks" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Rollbacks</h3><h4 id="h-overview" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Overview</h4><p>Rollback is the process of reverting a service to a previous stable version if the current deployment fails or shows degraded performance. This feature ensures that services can quickly recover from faulty updates.</p><h4 id="h-how-it-works" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">How It Works</h4><ul><li><p><strong>Automatic Rollbacks</strong>: If the rolling update encounters issues (e.g., health checks fail), Docker Swarm can automatically rollback to the previous version of the service.</p></li><li><p><strong>Manual Rollbacks</strong>: You can also trigger a rollback manually if issues are discovered after the deployment.</p></li></ul><h4 id="h-example-configuration" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Example Configuration</h4><p>To enable automatic rollbacks, you can specify the <code>failure_action</code> in the <code>update_config</code>:</p><pre data-type="codeBlock" text="update_config:
  parallelism: 2
  delay: 10s
  failure_action: rollback
"><code><span class="hljs-attr">update_config:</span>
  <span class="hljs-attr">parallelism:</span> <span class="hljs-number">2</span>
  <span class="hljs-attr">delay:</span> <span class="hljs-string">10s</span>
  <span class="hljs-attr">failure_action:</span> <span class="hljs-string">rollback</span>
</code></pre><p>To manually trigger a rollback, you can use the following Docker CLI command:</p><pre data-type="codeBlock" text="docker service update --rollback &lt;service_name&gt;
"><code>docker service update <span class="hljs-operator">-</span><span class="hljs-operator">-</span>rollback <span class="hljs-operator">&#x3C;</span>service_name<span class="hljs-operator">></span>
</code></pre><h3 id="h-resilience" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Resilience</h3><h4 id="h-overview" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Overview</h4><p>Resilience in Docker Swarm refers to the cluster&apos;s ability to handle failures and maintain service availability. Docker Swarm provides several features to ensure that services remain up and running despite node or container failures.</p><h4 id="h-key-features" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Key Features</h4><ol><li><p><strong>Service Replication</strong>:</p><ul><li><p>Docker Swarm ensures that the desired number of replicas for each service is running. If a container fails, Swarm automatically schedules a new one to maintain the specified replica count.</p></li></ul></li><li><p><strong>Health Checks</strong>:</p><ul><li><p>Health checks are used to monitor the state of services. If a service instance is unhealthy, Swarm will restart the container or move it to another node if necessary.</p></li></ul></li><li><p><strong>Automatic Rescheduling</strong>:</p><ul><li><p>If a node goes down, Docker Swarm reschedules the affected containers on other available nodes in the cluster to maintain service availability.</p></li></ul></li><li><p><strong>Load Balancing</strong>:</p><ul><li><p>Docker Swarm has built-in load balancing to distribute traffic across all healthy replicas of a service. This ensures that no single instance is overwhelmed and can handle traffic spikes effectively.</p></li></ul></li><li><p><strong>Overlay Networking</strong>:</p><ul><li><p>Swarm uses overlay networks to enable communication between services running on different nodes. This ensures that services can communicate reliably even in the event of node failures.</p></li></ul></li></ol><h3 id="h-example-configuration-for-resilience" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Example Configuration for Resilience</h3><p>Here&apos;s a configuration that incorporates several resilience features:</p><pre data-type="codeBlock" text="version: &apos;3.7&apos;

services:
  api:
    image: my-api:latest
    deploy:
      replicas: 3
      update_config:
        parallelism: 1
        delay: 10s
        failure_action: rollback
      restart_policy:
        condition: on-failure
        delay: 5s
        max_attempts: 3
      placement:
        constraints:
          - node.role == worker
    networks:
      - overlay_network

networks:
  overlay_network:
    driver: overlay
"><code><span class="hljs-attr">version:</span> <span class="hljs-string">'3.7'</span>

<span class="hljs-attr">services:</span>
  <span class="hljs-attr">api:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">my-api:latest</span>
    <span class="hljs-attr">deploy:</span>
      <span class="hljs-attr">replicas:</span> <span class="hljs-number">3</span>
      <span class="hljs-attr">update_config:</span>
        <span class="hljs-attr">parallelism:</span> <span class="hljs-number">1</span>
        <span class="hljs-attr">delay:</span> <span class="hljs-string">10s</span>
        <span class="hljs-attr">failure_action:</span> <span class="hljs-string">rollback</span>
      <span class="hljs-attr">restart_policy:</span>
        <span class="hljs-attr">condition:</span> <span class="hljs-string">on-failure</span>
        <span class="hljs-attr">delay:</span> <span class="hljs-string">5s</span>
        <span class="hljs-attr">max_attempts:</span> <span class="hljs-number">3</span>
      <span class="hljs-attr">placement:</span>
        <span class="hljs-attr">constraints:</span>
          <span class="hljs-bullet">-</span> <span class="hljs-string">node.role</span> <span class="hljs-string">==</span> <span class="hljs-string">worker</span>
    <span class="hljs-attr">networks:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">overlay_network</span>

<span class="hljs-attr">networks:</span>
  <span class="hljs-attr">overlay_network:</span>
    <span class="hljs-attr">driver:</span> <span class="hljs-string">overlay</span>
</code></pre><ul><li><p><strong>Replicas</strong>: Ensures three instances of the <code>api</code> service are running.</p></li><li><p><strong>Update Configuration</strong>: Configures rolling updates with rollback on failure.</p></li><li><p><strong>Restart Policy</strong>: Defines conditions for restarting containers that fail.</p></li><li><p><strong>Placement Constraints</strong>: Ensures the service runs on worker nodes.</p></li><li><p><strong>Overlay Network</strong>: Uses overlay networking for service communication.</p></li></ul><h3 id="h-summary" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Summary</h3><ul><li><p><strong>Rolling Updates</strong>: Gradually updates service instances to ensure minimal disruption. Parameters like parallelism, delay, and failure_action provide fine-grained control.</p></li><li><p><strong>Rollbacks</strong>: Allows automatic or manual reversion to a previous stable version if issues are encountered during updates.</p></li><li><p><strong>Resilience</strong>: Ensures high availability and fault tolerance through service replication, health checks, automatic rescheduling, load balancing, and overlay networking.</p></li></ul><p>These features make Docker Swarm a robust choice for managing containerized applications in production environments, ensuring both stability and flexibility in handling updates and failures.</p><h2 id="h-5-deploying-stateful-applications-in-docker-swarm" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">5. Deploying Stateful Applications in Docker Swarm</h2><ol><li><p><strong>Setup Docker Swarm:</strong> Initialize the Docker Swarm and add nodes to the Swarm.</p><pre data-type="codeBlock" text="docker swarm init
docker swarm join --token &lt;token&gt; &lt;manager_ip&gt;:&lt;port&gt;
"><code>docker swarm init
docker swarm join <span class="hljs-operator">-</span><span class="hljs-operator">-</span>token <span class="hljs-operator">&#x3C;</span>token<span class="hljs-operator">></span> <span class="hljs-operator">&#x3C;</span>manager_ip<span class="hljs-operator">></span>:<span class="hljs-operator">&#x3C;</span>port<span class="hljs-operator">></span>
</code></pre></li><li><p><strong>Create a Volume:</strong> Create a Docker volume that will be used for persistent storage.</p><pre data-type="codeBlock" text="docker volume create db_data
"><code>docker volume <span class="hljs-built_in">create</span> db_data
</code></pre></li><li><p><strong>Deploy the Stateful Service:</strong> Use a Docker Compose file to define the service with constraints to ensure the service runs on the node with the volume.</p><p><strong>Example</strong> <code>docker-compose.yml</code>:</p><pre data-type="codeBlock" text="version: &apos;3.8&apos;
services:
  db:
    image: postgres:13
    volumes:
      - db_data:/var/lib/postgresql/data
    deploy:
      placement:
        constraints:
          - node.hostname == manager1  # Replace with the hostname of the node with the volume
volumes:
  db_data:
    external: true
"><code><span class="hljs-attr">version:</span> <span class="hljs-string">'3.8'</span>
<span class="hljs-attr">services:</span>
  <span class="hljs-attr">db:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">postgres:13</span>
    <span class="hljs-attr">volumes:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">db_data:/var/lib/postgresql/data</span>
    <span class="hljs-attr">deploy:</span>
      <span class="hljs-attr">placement:</span>
        <span class="hljs-attr">constraints:</span>
          <span class="hljs-bullet">-</span> <span class="hljs-string">node.hostname</span> <span class="hljs-string">==</span> <span class="hljs-string">manager1</span>  <span class="hljs-comment"># Replace with the hostname of the node with the volume</span>
<span class="hljs-attr">volumes:</span>
  <span class="hljs-attr">db_data:</span>
    <span class="hljs-attr">external:</span> <span class="hljs-literal">true</span>
</code></pre></li><li><p><strong>Deploy the Stack:</strong> Deploy the stack using the Docker Compose file.</p><pre data-type="codeBlock" text="docker stack deploy -c docker-compose.yml my_stack
"><code>docker stack deploy <span class="hljs-operator">-</span>c docker<span class="hljs-operator">-</span>compose.yml my_stack
</code></pre></li></ol><h3 id="h-ensuring-containers-are-launched-on-the-same-node" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Ensuring Containers are Launched on the Same Node</h3><p>To ensure that containers are launched on the same node that has the volume, you can use node constraints and labels.</p><ol><li><p><strong>Label the Node:</strong> Label the node that has the volume with a custom label.</p><pre data-type="codeBlock" text="docker node update --label-add db_node=true &lt;node_name&gt;
"><code>docker node update <span class="hljs-operator">-</span><span class="hljs-operator">-</span>label<span class="hljs-operator">-</span>add db_node<span class="hljs-operator">=</span><span class="hljs-literal">true</span> <span class="hljs-operator">&#x3C;</span>node_name<span class="hljs-operator">></span>
</code></pre></li><li><p><strong>Update the Compose File:</strong> Update the Docker Compose file to use the node label for placement constraints.</p><p><strong>Updated</strong> <code>docker-compose.yml</code>:</p><pre data-type="codeBlock" text="version: &apos;3.8&apos;
services:
  db:
    image: postgres:13
    volumes:
      - db_data:/var/lib/postgresql/data
    deploy:
      placement:
        constraints:
          - node.labels.db_node == true
volumes:
  db_data:
    external: true
"><code>version: <span class="hljs-string">'3.8'</span>
services:
  db:
    image: postgres:<span class="hljs-number">13</span>
    volumes:
      <span class="hljs-operator">-</span> db_data:<span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>lib<span class="hljs-operator">/</span>postgresql<span class="hljs-operator">/</span>data
    deploy:
      placement:
        constraints:
          <span class="hljs-operator">-</span> node.labels.db_node <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-literal">true</span>
volumes:
  db_data:
    <span class="hljs-keyword">external</span>: <span class="hljs-literal">true</span>
</code></pre></li></ol><h3 id="h-example-scenario" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Example Scenario</h3><ol><li><p><strong>Initialize Swarm:</strong></p><pre data-type="codeBlock" text="docker swarm init
"><code>docker swarm <span class="hljs-keyword">init</span>
</code></pre></li><li><p><strong>Add Nodes:</strong> Add worker nodes to the Swarm. For example, add two worker nodes.</p><pre data-type="codeBlock" text="docker swarm join --token &lt;worker_token&gt; &lt;manager_ip&gt;:2377
"><code>docker swarm join <span class="hljs-operator">-</span><span class="hljs-operator">-</span>token <span class="hljs-operator">&#x3C;</span>worker_token<span class="hljs-operator">></span> <span class="hljs-operator">&#x3C;</span>manager_ip<span class="hljs-operator">></span>:<span class="hljs-number">2377</span>
</code></pre></li><li><p><strong>Label the Node with the Volume:</strong> Assume <code>manager1</code> is the node where you want the database to run and where the volume is created.</p><pre data-type="codeBlock" text="docker node update --label-add db_node=true manager1
"><code>docker node update <span class="hljs-operator">-</span><span class="hljs-operator">-</span>label<span class="hljs-operator">-</span>add db_node<span class="hljs-operator">=</span><span class="hljs-literal">true</span> manager1
</code></pre></li><li><p><strong>Create External Volume:</strong> Create the volume on <code>manager1</code>.</p><pre data-type="codeBlock" text="docker volume create db_data
"><code>docker volume <span class="hljs-built_in">create</span> db_data
</code></pre></li><li><p><strong>Deploy the Stack:</strong> Deploy the stack with the updated <code>docker-compose.yml</code>:</p><pre data-type="codeBlock" text="version: &apos;3.8&apos;
services:
  db:
    image: postgres:13
    volumes:
      - db_data:/var/lib/postgresql/data
    deploy:
      placement:
        constraints:
          - node.labels.db_node == true
volumes:
  db_data:
    external: true
"><code>version: <span class="hljs-string">'3.8'</span>
services:
  db:
    image: postgres:<span class="hljs-number">13</span>
    volumes:
      <span class="hljs-operator">-</span> db_data:<span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>lib<span class="hljs-operator">/</span>postgresql<span class="hljs-operator">/</span>data
    deploy:
      placement:
        constraints:
          <span class="hljs-operator">-</span> node.labels.db_node <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-literal">true</span>
volumes:
  db_data:
    <span class="hljs-keyword">external</span>: <span class="hljs-literal">true</span>
</code></pre><p>Deploy the stack:</p><pre data-type="codeBlock" text="docker stack deploy -c docker-compose.yml my_stack
"><code>docker stack deploy <span class="hljs-operator">-</span>c docker<span class="hljs-operator">-</span>compose.yml my_stack
</code></pre></li></ol><h3 id="h-considerations" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Considerations</h3><ul><li><p><strong>Node Failure:</strong> If the node with the volume fails, manual intervention is required to recover the volume and redeploy the service. High availability for stateful services might involve using replicated storage solutions like NFS, GlusterFS, or cloud-based storage services.</p></li><li><p><strong>Performance:</strong> Ensure the chosen node can handle the I/O requirements of the stateful application to avoid performance bottlenecks.</p></li><li><p><strong>Backup:</strong> Regularly backup the volumes to prevent data loss.</p></li></ul><h3 id="h-conclusion" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Conclusion</h3><p>Deploying stateful applications like databases in Docker Swarm involves careful planning and configuration to ensure data persistence and reliability. By using Docker volumes, node labels, and placement constraints, you can effectively manage and deploy stateful services. While Docker Swarm provides the necessary tools for basic stateful deployments, more advanced setups might require additional storage solutions to ensure high availability and resilience.</p><h2 id="h-6-context-of-labels-in-docker-swarm" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">6. Context of Labels in Docker Swarm</h2><ol><li><p><strong>Cluster Scope:</strong></p><ul><li><p><strong>Service Labels:</strong> The labels you use in the <code>labels</code> section of a service definition are scoped to the Docker Swarm cluster. They can influence how external systems like Traefik interact with services within the entire Swarm.</p></li><li><p><strong>Node Labels:</strong> Placement constraints based on node labels (e.g., <code>node.labels.prometheus.data == true</code>) are used to determine on which nodes within the Swarm cluster a service can be scheduled.</p></li></ul></li><li><p><strong>Project Namespace:</strong></p><ul><li><p>When you deploy a stack using Docker Compose or <code>docker stack deploy</code>, Docker Swarm uses the stack name as a namespace for services, networks, and volumes. This means that the labels and constraints you define are associated with the services within that stack (project namespace), but their functionality, such as influencing Traefik&apos;s behavior or node placement, applies cluster-wide.</p></li></ul></li></ol><h3 id="h-detailed-explanation" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Detailed Explanation</h3><h4 id="h-service-labels-in-docker-swarm" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Service Labels in Docker Swarm</h4><ul><li><p><strong>Service Configuration and Traefik Integration:</strong> The service labels (e.g., <code>traefik.enable</code>, <code>traefik.http.routers.prometheus.entrypoints</code>) are used by Traefik to configure routing and load balancing. Traefik, running within the Swarm cluster, monitors these labels to dynamically adjust its configuration based on the services running in the cluster.</p><p>For example:</p><pre data-type="codeBlock" text="labels:
  - traefik.enable=true
  - traefik.http.routers.prometheus.entrypoints=https
  - traefik.http.routers.prometheus.middlewares=admin-ip,admin-auth
  - traefik.http.services.prometheus.loadbalancer.server.port=9090
"><code>labels:
  <span class="hljs-operator">-</span> traefik.enable=<span class="hljs-literal">true</span>
  <span class="hljs-operator">-</span> traefik.http.routers.prometheus.entrypoints=https
  <span class="hljs-operator">-</span> traefik.http.routers.prometheus.middlewares=admin<span class="hljs-operator">-</span>ip,admin<span class="hljs-operator">-</span>auth
  <span class="hljs-operator">-</span> traefik.http.services.prometheus.loadbalancer.server.port=<span class="hljs-number">9090</span>
</code></pre><p>These labels instruct Traefik to enable routing for the Prometheus service, specify the HTTPS entry point, apply specific middlewares, and route traffic to port 9090 inside the Prometheus container.</p></li></ul><h4 id="h-node-labels-and-placement-constraints" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Node Labels and Placement Constraints</h4><ul><li><p><strong>Node Placement:</strong> Node labels are used to ensure that certain services run only on specific nodes within the Swarm cluster. This is useful for scenarios where specific hardware or storage configurations are required.</p><p>For example:</p><pre data-type="codeBlock" text="deploy:
  placement:
    constraints:
      - node.labels.prometheus.data == true
"><code>deploy:
  placement:
    constraints:
      <span class="hljs-operator">-</span> node.labels.prometheus.data <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-literal">true</span>
</code></pre><p>This placement constraint ensures that the Prometheus service is scheduled only on nodes that have the label <code>prometheus.data</code> set to <code>true</code>.</p></li></ul><h4 id="h-project-namespace" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Project Namespace</h4><ul><li><p><strong>Stack Deployment:</strong> When deploying a stack with <code>docker stack deploy -c docker-compose.yml my_stack</code>, Docker Swarm uses <code>my_stack</code> as a namespace. Services, networks, and volumes defined in the compose file are prefixed with this namespace. This namespacing helps in managing multiple projects or stacks within the same Swarm cluster without conflicts.</p><p>For example, if you have two stacks:</p><pre data-type="codeBlock" text="docker stack deploy -c docker-compose.yml prometheus_stack
docker stack deploy -c another-compose.yml logging_stack
"><code>docker stack deploy <span class="hljs-operator">-</span>c docker<span class="hljs-operator">-</span>compose.yml prometheus_stack
docker stack deploy <span class="hljs-operator">-</span>c another<span class="hljs-operator">-</span>compose.yml logging_stack
</code></pre><p>The services in these stacks will be namespaced accordingly:</p><ul><li><p><code>prometheus_stack_prometheus</code></p></li><li><p><code>logging_stack_logging_service</code></p></li></ul></li></ul><h3 id="h-conclusion" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Conclusion</h3><ul><li><p><strong>Labels:</strong> The labels used in your service definitions operate within the scope of the Docker Swarm cluster, allowing tools like Traefik to dynamically adjust configurations based on services running anywhere in the cluster.</p></li><li><p><strong>Placement Constraints:</strong> Node labels and placement constraints ensure services are deployed on suitable nodes within the Swarm cluster.</p></li><li><p><strong>Namespaces:</strong> When deploying stacks, Docker Swarm namespaces services, networks, and volumes to avoid conflicts and manage multiple projects within the same cluster.</p></li></ul><p>This setup allows for flexible and powerful management of services and resources within a Docker Swarm cluster, leveraging labels and constraints to ensure optimal placement and configuration.</p><h2 id="h-7-load-balancing-in-docker-swarm" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">7. Load Balancing in Docker Swarm</h2><h4 id="h-overview" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Overview</h4><p>Load balancing in Docker Swarm distributes network traffic evenly across multiple service instances to ensure that no single instance is overwhelmed and to provide high availability.</p><h4 id="h-key-features" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Key Features</h4><ol><li><p><strong>Internal Load Balancing</strong>:</p><ul><li><p>Docker Swarm uses an internal load balancer (VIP-based) to distribute requests among service replicas.</p></li></ul></li><li><p><strong>DNS-Based Load Balancing</strong>:</p><ul><li><p>Service discovery via DNS allows clients to resolve the service name to multiple IP addresses, distributing traffic among service replicas.</p></li></ul></li><li><p><strong>Ingress Load Balancing</strong>:</p><ul><li><p>Swarm&apos;s ingress network allows external traffic to be routed to the appropriate service based on published ports.</p></li></ul></li><li><p><strong>Sticky Sessions with Traefik/HAproxy/Nginx</strong>:</p><ul><li><p>Docker Swarm supports sticky sessions when deploying Traefik/HAproxy/Nginx, ensuring that subsequent requests from the same client are directed to the same service instance.</p></li></ul></li></ol><h4 id="h-how-it-works" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">How It Works</h4><ol><li><p><strong>Internal Load Balancing</strong>:</p><ul><li><p>When a service is deployed, Docker Swarm assigns a virtual IP (VIP) to the service. Requests to the service&apos;s VIP are distributed across the service&apos;s replicas.</p><pre data-type="codeBlock" text="version: &apos;3.7&apos;

services:
  web:
    image: my-web-app:latest
    deploy:
      replicas: 3
      endpoint_mode: vip
    ports:
      - &quot;80:80&quot;
"><code><span class="hljs-attr">version:</span> <span class="hljs-string">'3.7'</span>

<span class="hljs-attr">services:</span>
  <span class="hljs-attr">web:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">my-web-app:latest</span>
    <span class="hljs-attr">deploy:</span>
      <span class="hljs-attr">replicas:</span> <span class="hljs-number">3</span>
      <span class="hljs-attr">endpoint_mode:</span> <span class="hljs-string">vip</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">"80:80"</span>
</code></pre></li></ul></li><li><p><strong>DNS-Based Load Balancing</strong>:</p><ul><li><p>Docker Swarm uses DNS round-robin for load balancing. Each service name resolves to multiple IP addresses, corresponding to the service&apos;s replicas.</p><pre data-type="codeBlock" text="version: &apos;3.7&apos;

services:
  web:
    image: my-web-app:latest
    deploy:
      replicas: 3
      endpoint_mode: dnsrr
    ports:
      - &quot;80:80&quot;
"><code><span class="hljs-attr">version:</span> <span class="hljs-string">'3.7'</span>

<span class="hljs-attr">services:</span>
  <span class="hljs-attr">web:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">my-web-app:latest</span>
    <span class="hljs-attr">deploy:</span>
      <span class="hljs-attr">replicas:</span> <span class="hljs-number">3</span>
      <span class="hljs-attr">endpoint_mode:</span> <span class="hljs-string">dnsrr</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">"80:80"</span>
</code></pre></li></ul></li><li><p><strong>Ingress Load Balancing</strong>:</p><ul><li><p>Docker Swarm&apos;s ingress network routes incoming traffic to the appropriate service based on published ports. This is handled transparently by Docker Swarm.</p><pre data-type="codeBlock" text="version: &apos;3.7&apos;

services:
  web:
    image: my-web-app:latest
    deploy:
      replicas: 3
    ports:
      - &quot;80:80&quot;
"><code><span class="hljs-attr">version:</span> <span class="hljs-string">'3.7'</span>

<span class="hljs-attr">services:</span>
  <span class="hljs-attr">web:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">my-web-app:latest</span>
    <span class="hljs-attr">deploy:</span>
      <span class="hljs-attr">replicas:</span> <span class="hljs-number">3</span>
    <span class="hljs-attr">ports:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">"80:80"</span>
</code></pre></li></ul></li><li><p><strong>Sticky Sessions with Traefik</strong>:</p><ul><li><p>Sticky sessions with Traefik can be enabled using the <code>sessionAffinity</code> setting, ensuring client requests are routed to the same service instance.</p><pre data-type="codeBlock" text="version: &apos;3.7&apos;

services:
  web:
    image: my-web-app:latest
    deploy:
      replicas: 3
      labels:
        - traefik.http.services.web.loadbalancer.sticky=true
    ports:
      - &quot;80:80&quot;
"><code>version: <span class="hljs-string">'3.7'</span>

services:
  web:
    image: my<span class="hljs-operator">-</span>web<span class="hljs-operator">-</span>app:latest
    deploy:
      replicas: <span class="hljs-number">3</span>
      labels:
        <span class="hljs-operator">-</span> traefik.http.services.web.loadbalancer.sticky=<span class="hljs-literal">true</span>
    ports:
      <span class="hljs-operator">-</span> <span class="hljs-string">"80:80"</span>
</code></pre></li></ul></li></ol><h4 id="h-use-cases" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Use Cases</h4><ul><li><p><strong>High Availability</strong>: Ensures that services remain available and can handle high traffic volumes by distributing requests evenly.</p></li><li><p><strong>Fault Tolerance</strong>: If one service replica fails, traffic is automatically redirected to healthy replicas, maintaining service continuity.</p></li><li><p><strong>Scalability</strong>: Easily scale services up or down by adjusting the number of replicas, with load balancing automatically handling the traffic distribution.</p></li></ul><h3 id="h-summary" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Summary</h3><ul><li><p><strong>Overlay Networking</strong>: Provides secure, multi-host networking with service discovery and isolation. It&apos;s crucial for microservices architectures and multi-node deployments.</p></li><li><p><strong>Load Balancing</strong>: Distributes traffic evenly across service replicas, ensuring high availability, fault tolerance, and scalability. Docker Swarm supports VIP-based internal load balancing, DNS round-robin, and ingress load balancing with support for sticky sessions in Traefik/HAproxy/Nginx.</p></li></ul><p>These features make Docker Swarm a powerful tool for managing and orchestrating containerized applications in a resilient and scalable manner.</p><h2 id="h-8-portainer-on-docker-swarm" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">8. Portainer on Docker Swarm</h2><p>Portainer is a lightweight management UI that allows you to manage your Docker environments, including Docker Swarm clusters, through a simple and intuitive web interface. It simplifies the complexity of container orchestration and provides a centralized platform to monitor and manage your Docker infrastructure.</p><h4 id="h-key-features-of-portainer-for-docker-swarm" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Key Features of Portainer for Docker Swarm</h4><ol><li><p><strong>Intuitive Dashboard:</strong></p><ul><li><p>Provides an overview of your Swarm cluster, including node status, container health, and resource utilization.</p></li></ul></li><li><p><strong>Service Management:</strong></p><ul><li><p>Allows you to deploy, update, and scale services within the Swarm.</p></li><li><p>Visual interface for creating and managing Docker stacks using Compose files.</p></li></ul></li><li><p><strong>Container Management:</strong></p><ul><li><p>Detailed view of container logs, metrics, and real-time stats.</p></li><li><p>Easy container deployment, start, stop, and removal.</p></li></ul></li><li><p><strong>Volume and Network Management:</strong></p><ul><li><p>Create and manage Docker volumes and networks.</p></li><li><p>Attach volumes and networks to services and containers with ease.</p></li></ul></li><li><p><strong>Role-Based Access Control (RBAC):</strong></p><ul><li><p>Manage users and define roles to control access to various features and resources within the Portainer interface.</p></li></ul></li><li><p><strong>Registry Management:</strong></p><ul><li><p>Integration with Docker Hub, private registries, and other container registries.</p></li><li><p>Manage and deploy images from multiple registries.</p></li></ul></li><li><p><strong>Backup and Restore:</strong></p><ul><li><p>Easily backup and restore Portainer configurations and Docker environments.</p></li></ul></li></ol><h4 id="h-installing-portainer-on-docker-swarm" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Installing Portainer on Docker Swarm</h4><p>To install Portainer on Docker Swarm, follow these steps:</p><ol><li><p><strong>Deploy Portainer using a Docker Stack:</strong> Create a <code>portainer-agent-stack.yml</code> file with the following content:</p><pre data-type="codeBlock" text="version: &apos;3.8&apos;

services:
  agent:
    image: portainer/agent
    environment:
      AGENT_CLUSTER_ADDR: tasks.agent
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /var/lib/docker/volumes:/var/lib/docker/volumes
    networks:
      - portainer_agent_network
    deploy:
      mode: global
      placement:
        constraints: [node.platform.os == linux]

  portainer:
    image: portainer/portainer-ce
    command: -H tcp://tasks.agent:9001 --tlsskipverify
    ports:
      - &quot;9000:9000&quot;
    volumes:
      - portainer_data:/data
    networks:
      - portainer_agent_network
    deploy:
      replicas: 1
      placement:
        constraints: [node.role == manager]

volumes:
  portainer_data:

networks:
  portainer_agent_network:
"><code>version: <span class="hljs-string">'3.8'</span>

services:
  agent:
    image: portainer<span class="hljs-operator">/</span>agent
    environment:
      AGENT_CLUSTER_ADDR: tasks.agent
    volumes:
      <span class="hljs-operator">-</span> <span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>run<span class="hljs-operator">/</span>docker.sock:<span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>run<span class="hljs-operator">/</span>docker.sock
      <span class="hljs-operator">-</span> <span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>lib<span class="hljs-operator">/</span>docker<span class="hljs-operator">/</span>volumes:<span class="hljs-operator">/</span><span class="hljs-keyword">var</span><span class="hljs-operator">/</span>lib<span class="hljs-operator">/</span>docker<span class="hljs-operator">/</span>volumes
    networks:
      <span class="hljs-operator">-</span> portainer_agent_network
    deploy:
      mode: <span class="hljs-keyword">global</span>
      placement:
        constraints: [node.platform.os <span class="hljs-operator">=</span><span class="hljs-operator">=</span> linux]

  portainer:
    image: portainer<span class="hljs-operator">/</span>portainer<span class="hljs-operator">-</span>ce
    command: <span class="hljs-operator">-</span>H tcp:<span class="hljs-comment">//tasks.agent:9001 --tlsskipverify</span>
    ports:
      <span class="hljs-operator">-</span> <span class="hljs-string">"9000:9000"</span>
    volumes:
      <span class="hljs-operator">-</span> portainer_data:<span class="hljs-operator">/</span>data
    networks:
      <span class="hljs-operator">-</span> portainer_agent_network
    deploy:
      replicas: <span class="hljs-number">1</span>
      placement:
        constraints: [node.role <span class="hljs-operator">=</span><span class="hljs-operator">=</span> manager]

volumes:
  portainer_data:

networks:
  portainer_agent_network:
</code></pre></li><li><p><strong>Deploy the Stack:</strong> Deploy the stack using the Docker CLI:</p><pre data-type="codeBlock" text="docker stack deploy -c portainer-agent-stack.yml portainer
"><code>docker stack deploy <span class="hljs-operator">-</span>c portainer<span class="hljs-operator">-</span>agent<span class="hljs-operator">-</span>stack.yml portainer
</code></pre></li><li><p><strong>Access Portainer:</strong> Once the stack is deployed, Portainer will be accessible via your browser at <code>http://&lt;manager-node-ip&gt;:9000</code>. The first time you access Portainer, you will be prompted to create an admin user.</p></li></ol><h4 id="h-managing-docker-swarm-with-portainer" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Managing Docker Swarm with Portainer</h4><p>After deploying Portainer, you can start managing your Docker Swarm cluster through its web interface. Here are some tasks you can perform:</p><ol><li><p><strong>Dashboard Overview:</strong></p><ul><li><p>Get a high-level view of your Swarm cluster, including node statuses, running services, and resource usage.</p></li></ul></li><li><p><strong>Service Deployment:</strong></p><ul><li><p>Use the &quot;App Templates&quot; or the &quot;Stacks&quot; feature to deploy new services using Docker Compose files. You can visually configure and deploy services, set environment variables, manage replicas, and more.</p></li></ul></li><li><p><strong>Scaling Services:</strong></p><ul><li><p>Easily scale services up or down by adjusting the number of replicas through the Portainer interface.</p></li></ul></li><li><p><strong>Monitoring and Logs:</strong></p><ul><li><p>Monitor container performance metrics and view real-time logs. This helps in diagnosing issues and maintaining the health of your applications.</p></li></ul></li><li><p><strong>Volume and Network Management:</strong></p><ul><li><p>Create and manage Docker volumes and networks. Attach them to services to ensure data persistence and facilitate inter-container communication.</p></li></ul></li><li><p><strong>User and Access Management:</strong></p><ul><li><p>Create users and define roles with specific permissions. This helps in managing who can access and modify different parts of your Docker environment.</p></li></ul></li><li><p><strong>Backup and Restore:</strong></p><ul><li><p>Use Portainer&apos;s built-in tools to backup and restore configurations, ensuring that you can recover quickly in case of an issue.</p></li></ul></li></ol><h4 id="h-conclusion" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">Conclusion</h4><p>Portainer significantly enhances the management of Docker Swarm by providing a user-friendly web interface that simplifies many of the tasks associated with container orchestration. Its features such as service management, container monitoring, and RBAC make it a valuable tool for any DevOps team working with Docker Swarm. By integrating Portainer into your Swarm environment, you can achieve greater efficiency, better resource management, and enhanced visibility into your containerized applications.</p><h2 id="h-9-portainer-vs-swarmpit" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">9. Portainer vs Swarmpit</h2><p>Both Portainer and Swarmpit are excellent tools for managing Docker Swarm clusters, each with its strengths and ideal use cases.</p><p><strong>Portainer</strong> is highly versatile, supporting multiple orchestrators (Docker Swarm, standalone Docker, Kubernetes) and offering a comprehensive set of features suitable for larger teams and complex environments. Its robust RBAC system and extensive documentation make it a strong choice for organizations requiring detailed user management and access controls.</p><p><strong>Swarmpit</strong>, on the other hand, is designed specifically for Docker Swarm and provides a streamlined, real-time interface for managing Swarm clusters. It is ideal for smaller to medium-sized teams or those focusing exclusively on Docker Swarm, thanks to its simplicity and focus on essential Swarm features.</p><p>Choosing between Portainer and Swarmpit depends on your specific needs, environment complexity, and user management requirements. For a versatile, feature-rich solution, Portainer is the way to go. For a Swarm-focused, straightforward management tool, Swarmpit is an excellent choice.</p><h2 id="h-10-portainer-interface" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">10. Portainer Interface</h2><p>The menu on the left side shows several icons, each representing different sections or functionalities within Portainer. Here is a description of each section from top to bottom:</p><ol><li><p><strong>Dashboard</strong>:</p><ul><li><p><strong>Icon</strong>: A combination of arrows pointing outward (cross).</p></li><li><p><strong>Function</strong>: Provides an overview of the entire Docker environment, including resource usage and system status.</p></li></ul></li><li><p><strong>Home</strong>:</p><ul><li><p><strong>Icon</strong>: A house.</p></li><li><p><strong>Function</strong>: Takes you to the main landing page or home screen of Portainer.</p></li></ul></li><li><p><strong>Templates</strong>:</p><ul><li><p><strong>Icon</strong>: A palette.</p></li><li><p><strong>Function</strong>: Access and manage application templates for easy deployment of commonly used applications.</p></li></ul></li><li><p><strong>Stacks</strong>:</p><ul><li><p><strong>Icon</strong>: A stack of layers.</p></li><li><p><strong>Function</strong>: Manage Docker stacks, which are groups of services defined by a Docker Compose file.</p></li></ul></li><li><p><strong>Services</strong>:</p><ul><li><p><strong>Icon</strong>: A collection of blocks.</p></li><li><p><strong>Function</strong>: Manage individual Docker services running within your environment.</p></li></ul></li><li><p><strong>Containers</strong>:</p><ul><li><p><strong>Icon</strong>: A single block.</p></li><li><p><strong>Function</strong>: Manage Docker containers, including starting, stopping, and inspecting containers.</p></li></ul></li><li><p><strong>Images</strong>:</p><ul><li><p><strong>Icon</strong>: A picture frame.</p></li><li><p><strong>Function</strong>: Manage Docker images, including pulling images from registries and deleting unused images.</p></li></ul></li><li><p><strong>Networks</strong>:</p><ul><li><p><strong>Icon</strong>: Connected nodes.</p></li><li><p><strong>Function</strong>: Manage Docker networks, which handle communication between containers and services.</p></li></ul></li><li><p><strong>Volumes</strong>:</p><ul><li><p><strong>Icon</strong>: A disk or volume.</p></li><li><p><strong>Function</strong>: Manage Docker volumes, which are used for persistent storage across container restarts.</p></li></ul></li><li><p><strong>Secrets</strong>:</p><ul><li><p><strong>Icon</strong>: A key.</p></li><li><p><strong>Function</strong>: Manage Docker secrets, which are used to securely pass sensitive information to containers.</p></li></ul></li><li><p><strong>Configs</strong>:</p><ul><li><p><strong>Icon</strong>: A document.</p></li><li><p><strong>Function</strong>: Manage Docker configs, which provide configuration data to services.</p></li></ul></li><li><p><strong>Events</strong>:</p><ul><li><p><strong>Icon</strong>: A list with check marks.</p></li><li><p><strong>Function</strong>: View events related to your Docker environment, which can help in auditing and troubleshooting.</p></li></ul></li><li><p><strong>Users</strong>:</p><ul><li><p><strong>Icon</strong>: Multiple user figures.</p></li><li><p><strong>Function</strong>: Manage Portainer users and their access permissions.</p></li></ul></li><li><p><strong>Teams</strong>:</p><ul><li><p><strong>Icon</strong>: A group of people.</p></li><li><p><strong>Function</strong>: Manage user teams within Portainer, facilitating role-based access control.</p></li></ul></li><li><p><strong>Roles</strong>:</p><ul><li><p><strong>Icon</strong>: A shield.</p></li><li><p><strong>Function</strong>: Define and manage roles for users and teams, controlling their access and permissions.</p></li></ul></li><li><p><strong>Settings</strong>:</p><ul><li><p><strong>Icon</strong>: A gear or cog.</p></li><li><p><strong>Function</strong>: Configure various settings of the Portainer application itself.</p></li></ul></li><li><p><strong>Extensions</strong>:</p><ul><li><p><strong>Icon</strong>: A puzzle piece.</p></li><li><p><strong>Function</strong>: Manage and configure Portainer extensions that enhance its functionality.</p></li></ul></li></ol><p>This comprehensive menu allows users to efficiently manage and configure their Docker environments, providing a wide range of functionalities through an intuitive user interface.</p><h2 id="h-11-configs-in-portainer" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">11. Configs in Portainer</h2><p>In Portainer, <strong>Configs</strong> are used to manage configuration data that can be used by Docker services. They provide a way to store and distribute configuration files or settings that your containers can use. This helps in maintaining consistency and security for configuration data, as it is managed and distributed centrally within the Docker Swarm.</p><h3 id="h-key-features-of-configs-in-portainer" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Key Features of Configs in Portainer</h3><ol><li><p><strong>Centralized Management</strong>:</p><ul><li><p>Configs provide a centralized way to manage configuration files. You can create, update, and delete configurations from the Portainer interface.</p></li></ul></li><li><p><strong>Secure Distribution</strong>:</p><ul><li><p>Configs are securely distributed to the containers that need them. Docker ensures that the configuration data is only accessible to the containers that require it.</p></li></ul></li><li><p><strong>Version Control</strong>:</p><ul><li><p>Managing configs through Portainer allows for version control and easy updates. You can replace or update configs without redeploying your services, ensuring that the latest configuration is always in use.</p></li></ul></li><li><p><strong>Integration with Services</strong>:</p><ul><li><p>Configs can be easily integrated into Docker services. When deploying a service, you can specify which configs should be used, and Docker will automatically provide these to the service.</p></li></ul></li><li><p><strong>Simplified Configuration</strong>:</p><ul><li><p>Using configs simplifies the configuration management of your services. Instead of hardcoding configuration data into your Dockerfiles or passing them as environment variables, you can use configs to manage this data separately.</p></li></ul></li></ol><h3 id="h-how-to-use-configs-in-portainer" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">How to Use Configs in Portainer</h3><ol><li><p><strong>Creating a Config</strong>:</p><ul><li><p>In Portainer, navigate to the Configs section and create a new config. You can specify the name and provide the content of the configuration file.</p></li></ul></li><li><p><strong>Assigning Configs to Services</strong>:</p><ul><li><p>When you create or update a service, you can specify the configs that the service needs. These configs are then mounted into the container&apos;s filesystem, making them accessible to the application running inside.</p></li></ul></li><li><p><strong>Updating Configs</strong>:</p><ul><li><p>You can update the content of a config through the Portainer UI. Once updated, any service using the config will automatically receive the updated version.</p></li></ul></li><li><p><strong>Deleting Configs</strong>:</p><ul><li><p>Unused configs can be deleted from the Portainer interface. However, ensure that no running services depend on the config before deletion to avoid service disruption.</p></li></ul></li></ol><h3 id="h-example" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Example</h3><p>Here&apos;s an example of how to define and use configs in a <code>docker-compose.yml</code> file for a Docker Swarm service:</p><pre data-type="codeBlock" text="version: &apos;3.7&apos;

configs:
  my_config:
    file: ./my_config.conf

services:
  my_service:
    image: my_image
    deploy:
      replicas: 3
    configs:
      - source: my_config
        target: /etc/my_service/my_config.conf
"><code><span class="hljs-attr">version:</span> <span class="hljs-string">'3.7'</span>

<span class="hljs-attr">configs:</span>
  <span class="hljs-attr">my_config:</span>
    <span class="hljs-attr">file:</span> <span class="hljs-string">./my_config.conf</span>

<span class="hljs-attr">services:</span>
  <span class="hljs-attr">my_service:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">my_image</span>
    <span class="hljs-attr">deploy:</span>
      <span class="hljs-attr">replicas:</span> <span class="hljs-number">3</span>
    <span class="hljs-attr">configs:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">source:</span> <span class="hljs-string">my_config</span>
        <span class="hljs-attr">target:</span> <span class="hljs-string">/etc/my_service/my_config.conf</span>
</code></pre><ul><li><p><strong>Config Definition</strong>:</p><pre data-type="codeBlock" text="configs:
  my_config:
    file: ./my_config.conf
"><code>configs:
  my_config:
    file: ./my_config.conf
</code></pre><p>This section defines a config named <code>my_config</code> with its content sourced from the local file <code>my_config.conf</code>.</p></li><li><p><strong>Service Usage</strong>:</p><pre data-type="codeBlock" text="services:
  my_service:
    image: my_image
    deploy:
      replicas: 3
    configs:
      - source: my_config
        target: /etc/my_service/my_config.conf
"><code><span class="hljs-attr">services:</span>
  <span class="hljs-attr">my_service:</span>
    <span class="hljs-attr">image:</span> <span class="hljs-string">my_image</span>
    <span class="hljs-attr">deploy:</span>
      <span class="hljs-attr">replicas:</span> <span class="hljs-number">3</span>
    <span class="hljs-attr">configs:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">source:</span> <span class="hljs-string">my_config</span>
        <span class="hljs-attr">target:</span> <span class="hljs-string">/etc/my_service/my_config.conf</span>
</code></pre><p>The service <code>my_service</code> specifies the config <code>my_config</code> and indicates that it should be mounted to <code>/etc/my_service/my_config.conf</code> inside the container.</p></li></ul><h3 id="h-benefits" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Benefits</h3><ul><li><p><strong>Consistency</strong>: Using configs ensures that the same configuration is used across all instances of a service.</p></li><li><p><strong>Security</strong>: Configs are managed by Docker and are only accessible to the containers that need them.</p></li><li><p><strong>Ease of Management</strong>: Portainer provides a user-friendly interface to manage configs, making it easy to update and distribute configuration data.</p></li></ul><p>By using configs in Portainer, you can improve the manageability, security, and consistency of your service configurations in a Docker Swarm environment.</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[Firefox 118 is out of scope of all security scanners. NIST is to blame.]]></title>
            <link>https://paragraph.com/@defi-in-security/firefox-118-is-out-of-scope-of-all-security-scanners-nist-is-to-blame</link>
            <guid>sdJuHt1V4Gh3AKOTd4QZ</guid>
            <pubDate>Thu, 27 Jun 2024 17:25:29 GMT</pubDate>
            <description><![CDATA[From FF 117 branch to 119 in official-cpe-dictionary_v2.3.xmlTL;DR: According to NIST CPE Dictionary there is no Firefox 118 branch. So it can&apos;t be vulnerable and all your security scanners won&apos;t see all the CVE&apos;s in it. The CPE Dictionary (Common Platform Enumeration) is a structured naming scheme for identifying and describing classes of applications, operating systems, and hardware devices within an information technology (IT) environment. It is part of a suite of specificat...]]></description>
            <content:encoded><![CDATA[<figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/68e7cf582f1d95f2417a9e1a7813aa24f33d0dbb776ae9829b509f806ce1f9fb.png" alt="From FF 117 branch to 119 in official-cpe-dictionary_v2.3.xml " blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">From FF 117 branch to 119 in official-cpe-dictionary_v2.3.xml</figcaption></figure><p><strong>TL;DR: According to NIST CPE Dictionary there is no Firefox 118 branch. So it can&apos;t be vulnerable and all your security scanners won&apos;t see all the CVE&apos;s in it.</strong></p><p><strong>The CPE Dictionary (Common Platform Enumeration)</strong> is a structured naming scheme for identifying and describing classes of applications, operating systems, and hardware devices within an information technology (IT) environment. It is part of a suite of specifications that aim to standardize the way IT assets are identified and managed, facilitating interoperability and improving security.</p><p><strong>Who Creates and Maintains the CPE Dictionary?</strong> The CPE Dictionary is created and maintained by the National Institute of Standards and Technology (NIST), a part of the U.S. Department of Commerce. NIST provides and supports the CPE Dictionary as part of its mission to enhance the security and resilience of the nation&apos;s cyber infrastructure.</p><p><strong>The development and upkeep of the CPE Dictionary involve the following steps:</strong></p><p><strong>Development of Standards</strong>: NIST collaborates with industry experts, cybersecurity professionals, and other stakeholders to develop and refine the CPE standards.</p><p><strong>Updating the Dictionary</strong>: NIST regularly updates the CPE Dictionary to include new platforms, technologies, and products. This involves a review and validation process to ensure accuracy and comprehensiveness.</p><p><strong>Community Contributions</strong>: While NIST oversees the CPE Dictionary, contributions and suggestions from the broader IT and cybersecurity communities are encouraged. These contributions help keep the dictionary up-to-date and relevant. The primary purpose of the CPE Dictionary is to provide a common language for identifying IT products and platforms. This standardization is crucial for vulnerability management.</p><p><strong>CPE consists of three main components:</strong></p><p><strong>CPE Name Format (CPE Name)</strong>: Defines the syntax and structure of names used to identify IT products and platforms.</p><p><strong>CPE Dictionary</strong>: A repository of standardized CPE names, each representing a specific product or platform.</p><p><strong>CPE Matching</strong>: Methods and algorithms used to match CPE names to actual IT assets, enabling automated identification and management.</p><p><code>Latest CPE Dictionary from NIST https://nvd.nist.gov/products/cpe</code><br><code>Name: official-cpe-dictionary_v2.3.xml</code><br><code>Size: 591753032 bytes (564 MiB)</code><br><code>SHA256: 570354C877506750E7935643DF64D1100E6225785D3EA17926AC46AD0AD2E47A</code></p><p>What does it do? It tracks existing software versions as CPE Name. When a CPE specifies a pattern of a vulnerable software version as &quot;&lt;122 Excluding 122&quot;, the filter goes through this CPE Name Dictionary, and all existing versions in this dictionary that match the specified criterion are interpolated, extracted, displayed or used in scans.</p><p><strong>In this dictionary, there simply isn&apos;t a CPE Name for Firefox 118 branch. It has only 117 and 119 and so on. This means that when all your scanners scan the system for CVEs, they work with the already expanded CPE Names expanded from this Dictionary. Since there is no branch for Firefox 118, it means there are no vulnerabilities listed for it.</strong></p><p>Another example from Mozilla is when a bug explicitly states that it pertains to version 118 and will not be fixed in 118: <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1830820">https://bugzilla.mozilla.org/show_bug.cgi?id=1830820</a>.</p><p>Meanwhile, in the CPE section at NIST for CVE-2023-5721 only version 117 is listed: <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://nvd.nist.gov/vuln/detail/CVE-2023-5721#range-13003528">https://nvd.nist.gov/vuln/detail/CVE-2023-5721#range-13003528</a></p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/fbacb5cdf9413d3ca3b0384b7e283241da95a09fba9ffeb565c2546bbd098f97.png" alt="CVE-2023-5721 on nvd.nist.gov without FF 118 branch" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">CVE-2023-5721 on nvd.nist.gov without FF 118 branch</figcaption></figure><p>This is the case for all FF (Firefox) bugs that have been found since the release of FF 118, including those found today, and there are plenty of them. Report was sent to NIST using E-mail address <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="mailto:cpe_dictionary@nist.gov">cpe_dictionary@nist.gov</a></p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[Открытый регулируемый рынок обмена криптовалют -- калитка в DeFi]]></title>
            <link>https://paragraph.com/@defi-in-security/defi</link>
            <guid>NENkXg8p3w9D6A4kH2hp</guid>
            <pubDate>Sun, 23 Jun 2024 22:29:40 GMT</pubDate>
            <description><![CDATA[Данное предложение является логическим дополнением к проекту "Ворота в DeFi. Платформа обменника с элементами Web3," который доступен по ссылке: https://mirror.xyz/0xdc519466f1cda17e8ae6735bB8652F47c0533CBe/ZEsfDn-Uyo5JtmAGqD6Jd7BPA0emaac1mZ8BHopt0zAЦельОблегчение простому пользователю, у которого нет опыта в DeFi, входа и покупки определенного DeFi-токена, который можно стейкать или иным образом получать нативный доход. Домохозяйка или студент в кампусе могут отсканировать СБП QR-код и приоб...]]></description>
            <content:encoded><![CDATA[<p>Данное предложение является логическим дополнением к проекту &quot;Ворота в DeFi. Платформа обменника с элементами Web3,&quot; который доступен по ссылке:</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://mirror.xyz/0xdc519466f1cda17e8ae6735bB8652F47c0533CBe/ZEsfDn-Uyo5JtmAGqD6Jd7BPA0emaac1mZ8BHopt0zA">https://mirror.xyz/0xdc519466f1cda17e8ae6735bB8652F47c0533CBe/ZEsfDn-Uyo5JtmAGqD6Jd7BPA0emaac1mZ8BHopt0zA</a></p><h2 id="h-cel" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Цель</h2><p>Облегчение простому пользователю, у которого нет опыта в DeFi, входа и покупки определенного DeFi-токена, который можно стейкать или иным образом получать нативный доход. Домохозяйка или студент в кампусе могут отсканировать СБП QR-код и приобрести обычный или автокомпаундирующий ликвидный токен-обертку. Приобретение обертки по СБП-коду становится единственным и достаточным шагом для полноценного использования и получения лучшей доходности. С учетом всех возможных комиссий при других способах данная доходность является оптимальной. При этом стандарты безопасности и работы с рисками обеспечиваются уровенем платформы-разработчика (заказчика).</p><h2 id="h-zadachi" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Задачи</h2><h3 id="h-1-issledovanie-rynka-platezhej-i-platyozhnyh-agentov-i-podgotovka-doklada-o-tekushem-sostoyanii" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">1. Исследование рынка платежей и платёжных агентов и подготовка доклада о текущем состоянии</h3><p>1.1. На первом шаге происходит изучение наиболее используемых электронных платежных инструментов, используемых среди населения бывшего СССР.</p><p>1.2. Изучение рынка платёжных посредников.</p><p>1.3. Подготовка соответствующих выводов и оценка стоимости всей операции в процентах по разным системам, возможные лимиты и прочие ограничивающие условия.</p><p>1.4. Постоянный поиск новых партнёров и платёжных агентов и оптимизация процесса взаимодействия.</p><h3 id="h-2-razrabotka-prilozheniya-agregatora-platyozhnyh-posrednikov-s-uchyotom-trebovanij-samyh-optimalnyh-iz-nih" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">2. Разработка приложения-агрегатора платёжных посредников с учётом требований самых оптимальных из них</h3><p>2.1. Предоставление первой ликвидности (например, 5000$) и разработка безопасного децентрализованного веб-кошелька, нативно работающего через Telegram WebApp функционал у ботов.</p><p>2.2. Разработка общих и открытых правил, стратегий.</p><p>2.3. Изучение работы агентов и их рисков, изучение методик снижения рисков для увеличения количества агентов, а также прочие действия, направленные на увеличение конкуренции среди агентов и снижение агентских комиссий.</p><h2 id="h-preimushestva-platformy" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Преимущества платформы</h2><p>Платформа, владеющая токеном и заинтересованная в росте осведомленности у пользователей о данном токене и росте количества пользователей, берёт на себя риски по хранению криптовалюты. Также оплачивает услуги арбитров, выступает платёжным посредником, гарантирующим безопасность сделки. Конкурентным преимуществом также является то, что платформа не ставит перед собой целью заработать на данном процессе, таким образом комиссии будут значительно меньше, чем у остальных.</p><h2 id="h-dopolnitelnye-mery" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Дополнительные меры</h2><p>Также необходимо постоянное расширение функционала, работа над рисками (удаление и баны и т.д.), публикация Roadmap, раздача поинтов с запланированным уменьшением объемов раздачи, действия направленные на увеличение уровня открытости и снижения рисков.</p><h2 id="h-centralizovannost-i-decentralizaciya" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Централизованность и децентрализация</h2><p>Централизованность на первых парах позволяет задать достаточный уровень безопасности, однако следует ставить соответствующие цели как в плане безопасности, отказоустойчивости и децентрализованности. Постоянная работа с рисками и адаптация архитектуры проекта.</p><h2 id="h-rezultat" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Результат</h2><p>Платформа оплачивает исследования и разработку приложения и обеспечивает прочую необходиму работу конкурентного рынка платежных посредников. При этом самостоятельно не являясь платежным посредником, а лишь сущностью которая выступает арбитром и третьей стороной и максимально открыто подходит к этому процессу и делегирует на уровень открытого кода всю возможную логику работы. В замен на экспертизу в разработке и соответствующий уровень безопасности платформа получает вовлечение новых пользователей токена. Открывается широкий простор для дальнейших действий по привлечению масс пользователей мессенджеров и прочих финансовых приложений из бывшего СССР.</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[Elasticsearch, Logstash, and Kibana (ELK) stack version 8 and efficiency]]></title>
            <link>https://paragraph.com/@defi-in-security/elasticsearch-logstash-and-kibana-elk-stack-version-8-and-efficiency</link>
            <guid>Z2uLy1d3oRRiW7z6BQSO</guid>
            <pubDate>Fri, 07 Jun 2024 23:04:38 GMT</pubDate>
            <description><![CDATA[Elasticsearch, Logstash, and Kibana (ELK) stack version 8, often referred to as the Elastic Stack, introduced several new features, enhancements, and improvements.Key TakeawaysEnhanced Performance and Efficiency: ELK Stack 8 introduces significant improvements in indexing and query performance, which can lead to more efficient CPU and memory usage. These enhancements help reduce indexing latency and improve throughput, optimizing resource utilization.Unified Data Collection with Elastic Agent...]]></description>
            <content:encoded><![CDATA[<p>Elasticsearch, Logstash, and Kibana (ELK) stack version 8, often referred to as the Elastic Stack, introduced several new features, enhancements, and improvements.</p><h3 id="h-key-takeaways" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Key Takeaways</h3><ol><li><p><strong>Enhanced Performance and Efficiency</strong>:</p><p>ELK Stack 8 introduces significant improvements in indexing and query performance, which can lead to more efficient CPU and memory usage. These enhancements help reduce indexing latency and improve throughput, optimizing resource utilization.</p></li><li><p><strong>Unified Data Collection with Elastic Agent</strong>:</p><p>The introduction of Elastic Agent replaces multiple Beats, simplifying the management of data collection and streamlining updates and configurations. This unified approach reduces administrative overhead and improves resource allocation, making it easier to deploy and manage data collection across infrastructure.</p></li><li><p><strong>Simplified Security and Data Management</strong>:</p><p>Security features, including TLS and HTTPS, are enabled by default, enhancing security and reducing configuration overhead. Additionally, new features like data streams improve index lifecycle management and data retention policies, leading to more efficient storage usage and optimized resource management.</p></li></ol><p>Here are some of the significant updates and improvements in ELK Stack version 8, particularly in terms of resource management and efficiency:</p><h3 id="h-key-new-features-and-improvements-in-elk-stack-8" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Key New Features and Improvements in ELK Stack 8</h3><ol><li><p><strong>Unified Agent (Elastic Agent)</strong>:</p><ul><li><p><strong>Description</strong>: Elastic Agent replaces Beats and offers a single, unified way to collect data from various sources.</p></li><li><p><strong>Benefits</strong>: Simplifies the management of data collection, reduces the need for multiple agents, and streamlines updates and configurations.</p></li></ul></li><li><p><strong>Simplified Security</strong>:</p><ul><li><p><strong>Description</strong>: Security features, including TLS for transport and HTTPS for Kibana, are enabled by default.</p></li><li><p><strong>Benefits</strong>: Simplifies the setup process, enhances security by default, and reduces configuration overhead.</p></li></ul></li><li><p><strong>Data Streams</strong>:</p><ul><li><p><strong>Description</strong>: Introduced data streams to simplify the management of time-series data.</p></li><li><p><strong>Benefits</strong>: Improves index lifecycle management and data retention policies, optimizing storage usage.</p></li></ul></li><li><p><strong>Indexing Performance Improvements</strong>:</p><ul><li><p><strong>Description</strong>: Enhanced indexing speed and efficiency.</p></li><li><p><strong>Benefits</strong>: Reduced indexing latency and improved throughput, which can lead to better CPU and memory usage.</p></li></ul></li><li><p><strong>New Aggregations and Query Enhancements</strong>:</p><ul><li><p><strong>Description</strong>: Enhanced query capabilities and new aggregation types.</p></li><li><p><strong>Benefits</strong>: Provides more efficient data retrieval and aggregation, potentially reducing CPU usage during complex queries.</p></li></ul></li><li><p><strong>Fleet Management</strong>:</p><ul><li><p><strong>Description</strong>: Introduced Fleet, a centralized way to manage Elastic Agents across your infrastructure.</p></li><li><p><strong>Benefits</strong>: Simplifies the deployment and management of agents, reducing administrative overhead and improving resource allocation.</p></li></ul></li><li><p><strong>Kibana Enhancements</strong>:</p><ul><li><p><strong>Description</strong>: New visualizations, dashboards, and user experience improvements.</p></li><li><p><strong>Benefits</strong>: Improved performance and usability of the Kibana interface, potentially reducing client-side resource usage.</p></li></ul></li><li><p><strong>Machine Learning Enhancements</strong>:</p><ul><li><p><strong>Description</strong>: Improvements in built-in machine learning capabilities.</p></li><li><p><strong>Benefits</strong>: Better performance and accuracy in anomaly detection and forecasting, with more efficient resource utilization.</p></li></ul></li></ol><h3 id="h-resource-management-and-efficiency" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Resource Management and Efficiency</h3><ul><li><p><strong>CPU and Memory Usage</strong>: ELK Stack 8 has seen improvements in indexing and query performance, which can lead to more efficient CPU and memory usage. However, the overall resource requirements might still be significant, depending on the workload and data volume.</p></li><li><p><strong>Storage (HDD)</strong>:</p><ul><li><p><strong>Data Streams</strong>: By simplifying the management of time-series data and improving index lifecycle management, the use of data streams can help optimize storage usage and improve retention policies.</p></li><li><p><strong>Indexing Efficiency</strong>: Enhanced indexing performance helps reduce the overhead on storage systems, making data ingestion more efficient.</p></li></ul></li><li><p><strong>Fleet and Elastic Agent</strong>:</p><ul><li><p><strong>Unified Management</strong>: By using a single, unified agent (Elastic Agent), resource management becomes more efficient compared to managing multiple Beats. This can lead to better resource utilization and simplified scaling.</p></li></ul></li></ul><h3 id="h-summary-of-resource-management-improvements" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Summary of Resource Management Improvements</h3><ul><li><p><strong>Improved Indexing and Query Performance</strong>: Enhancements in indexing and query performance can lead to more efficient CPU and memory usage.</p></li><li><p><strong>Unified Data Collection</strong>: The Elastic Agent reduces the overhead of managing multiple data collectors, leading to streamlined resource usage.</p></li><li><p><strong>Simplified Security Configuration</strong>: Enabling security features by default can reduce the complexity and resource overhead associated with configuring and maintaining security settings.</p></li><li><p><strong>Enhanced Data Management</strong>: Features like data streams and improved index lifecycle management contribute to more efficient storage usage.</p></li></ul><h3 id="h-conclusion" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Conclusion</h3><p>ELK Stack version 8 introduces several enhancements that can lead to better resource management and efficiency. While it might not necessarily reduce the baseline resource requirements significantly, it does provide more efficient ways to manage and utilize those resources. The improvements in indexing, querying, and data management, along with the unification of data collection through Elastic Agent, contribute to a more streamlined and resource-efficient stack.</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[Grafana vs. Kibana: A Comparative Analysis]]></title>
            <link>https://paragraph.com/@defi-in-security/grafana-vs-kibana-a-comparative-analysis</link>
            <guid>dJWSmJ73mWaysdHCMy3g</guid>
            <pubDate>Fri, 07 Jun 2024 22:40:42 GMT</pubDate>
            <description><![CDATA[Grafana and Kibana are two of the most popular open-source tools used for data visualization and monitoring. Here&apos;s a detailed comparison:1. Purpose and Core Use CaseGrafana:Primarily designed for time-series analytics.Excels in monitoring and observability use cases.Often paired with time-series databases like Prometheus, InfluxDB, and Graphite.Kibana:Part of the ELK (Elasticsearch, Logstash, Kibana) stack.Focuses on log and event data analysis.Best suited for searching, visualizing, an...]]></description>
            <content:encoded><![CDATA[<p><strong>Grafana</strong> and <strong>Kibana</strong> are two of the most popular open-source tools used for data visualization and monitoring. Here&apos;s a detailed comparison:</p><h4 id="h-1-purpose-and-core-use-case" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">1. <strong>Purpose and Core Use Case</strong></h4><ul><li><p><strong>Grafana</strong>:</p><ul><li><p>Primarily designed for time-series analytics.</p></li><li><p>Excels in monitoring and observability use cases.</p></li><li><p>Often paired with time-series databases like Prometheus, InfluxDB, and Graphite.</p></li></ul></li><li><p><strong>Kibana</strong>:</p><ul><li><p>Part of the ELK (Elasticsearch, Logstash, Kibana) stack.</p></li><li><p>Focuses on log and event data analysis.</p></li><li><p>Best suited for searching, visualizing, and analyzing log data stored in Elasticsearch.</p></li></ul></li></ul><h4 id="h-2-data-sources" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">2. <strong>Data Sources</strong></h4><ul><li><p><strong>Grafana</strong>:</p><ul><li><p>Supports a wide range of data sources including Prometheus, InfluxDB, Elasticsearch, MySQL, PostgreSQL, and more.</p></li><li><p>Allows combining multiple data sources in a single dashboard.</p></li></ul></li><li><p><strong>Kibana</strong>:</p><ul><li><p>Primarily works with Elasticsearch as its data source.</p></li><li><p>Designed to leverage Elasticsearch&apos;s full-text search capabilities.</p></li></ul></li></ul><h4 id="h-3-visualization-and-dashboarding" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">3. <strong>Visualization and Dashboarding</strong></h4><ul><li><p><strong>Grafana</strong>:</p><ul><li><p>Offers rich and flexible visualization options for time-series data.</p></li><li><p>Provides advanced features like templating, annotations, and alerting.</p></li><li><p>Highly customizable with support for plugins.</p></li></ul></li><li><p><strong>Kibana</strong>:</p><ul><li><p>Focuses on creating visualizations from structured and unstructured log data.</p></li><li><p>Supports various visualization types, including line charts, pie charts, histograms, and maps.</p></li><li><p>Has features for machine learning and anomaly detection.</p></li></ul></li></ul><h4 id="h-4-user-interface-and-experience" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">4. <strong>User Interface and Experience</strong></h4><ul><li><p><strong>Grafana</strong>:</p><ul><li><p>Intuitive and user-friendly interface for creating and managing dashboards.</p></li><li><p>Strong community support and frequent updates.</p></li></ul></li><li><p><strong>Kibana</strong>:</p><ul><li><p>Comprehensive interface with powerful querying capabilities using Kibana Query Language (KQL).</p></li><li><p>Provides dedicated UIs for managing Elasticsearch features like index patterns, machine learning jobs, and more.</p></li></ul></li></ul><h4 id="h-5-alerting-and-monitoring" class="text-xl font-header !mt-6 !mb-3 first:!mt-0 first:!mb-0">5. <strong>Alerting and Monitoring</strong></h4><ul><li><p><strong>Grafana</strong>:</p><ul><li><p>Built-in alerting capabilities.</p></li><li><p>Can send alerts to various channels like email, Slack, PagerDuty, and more.</p></li><li><p>Supports complex alert conditions based on multiple data sources.</p></li></ul></li><li><p><strong>Kibana</strong>:</p><ul><li><p>Alerting features are available through the X-Pack (commercial plugin).</p></li><li><p>Alerts can be created based on Elasticsearch queries and conditions.</p></li><li><p>Integration with Elasticsearch Watcher for complex alerting scenarios.</p></li></ul></li></ul>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
            <enclosure url="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/c669cb34e884019b7ba376493e98fc629289df29966414aec9a2a7ca8dcbfe8b.jpg" length="0" type="image/jpg"/>
        </item>
        <item>
            <title><![CDATA[Passing Trivy JSON data to Kibana to Logstash]]></title>
            <link>https://paragraph.com/@defi-in-security/passing-trivy-json-data-to-kibana-to-logstash</link>
            <guid>H6WUi0Q1qhtYJWhFOYfy</guid>
            <pubDate>Fri, 07 Jun 2024 20:39:53 GMT</pubDate>
            <description><![CDATA[Passing Trivy JSON data through Kibana to Logstash directly isn&apos;t a typical workflow, as Kibana is primarily designed for visualizing data stored in Elasticsearch rather than ingesting data. However, you can set up an ingestion pipeline using Logstash to handle incoming data and then visualize it in Kibana. Here’s how you can accomplish this by integrating Kibana, Logstash, and Elasticsearch efficiently.Step-by-Step Guide to Ingest Trivy JSON Data via LogstashSet Up the ELK Stack Using D...]]></description>
            <content:encoded><![CDATA[<p>Passing Trivy JSON data through Kibana to Logstash directly isn&apos;t a typical workflow, as Kibana is primarily designed for visualizing data stored in Elasticsearch rather than ingesting data. However, you can set up an ingestion pipeline using Logstash to handle incoming data and then visualize it in Kibana. Here’s how you can accomplish this by integrating Kibana, Logstash, and Elasticsearch efficiently.</p><h3 id="h-step-by-step-guide-to-ingest-trivy-json-data-via-logstash" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Step-by-Step Guide to Ingest Trivy JSON Data via Logstash</h3><ol><li><p><strong>Set Up the ELK Stack Using Docker Compose:</strong> Create a <code>docker-compose.yml</code> file to set up Elasticsearch, Kibana, and Logstash.</p><pre data-type="codeBlock" text="version: &apos;3.7&apos;

services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.17.9
    container_name: elasticsearch
    environment:
      - node.name=elasticsearch
      - discovery.type=single-node
      - cluster.name=trivy-cluster
      - xpack.security.enabled=false
      - bootstrap.memory_lock=true
      - &quot;ES_JAVA_OPTS=-Xms512m -Xmx512m&quot;
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - es_data:/usr/share/elasticsearch/data
    ports:
      - &quot;9200:9200&quot;
      - &quot;9300:9300&quot;

  kibana:
    image: docker.elastic.co/kibana/kibana:7.17.9
    container_name: kibana
    environment:
      - ELASTICSEARCH_HOSTS=http://elasticsearch:9200
    ports:
      - &quot;5601:5601&quot;
    depends_on:
      - elasticsearch

  logstash:
    image: docker.elastic.co/logstash/logstash:7.17.9
    container_name: logstash
    volumes:
      - ./logstash/pipeline:/usr/share/logstash/pipeline
    environment:
      - LS_JAVA_OPTS=&quot;-Xmx256m -Xms256m&quot;
    ports:
      - &quot;5044:5044&quot;
    depends_on:
      - elasticsearch

volumes:
  es_data:
    driver: local
"><code>version: <span class="hljs-string">'3.7'</span>

services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch<span class="hljs-operator">/</span>elasticsearch:<span class="hljs-number">7.17</span><span class="hljs-number">.9</span>
    container_name: elasticsearch
    environment:
      <span class="hljs-operator">-</span> node.<span class="hljs-built_in">name</span>=elasticsearch
      <span class="hljs-operator">-</span> discovery.type=single<span class="hljs-operator">-</span>node
      <span class="hljs-operator">-</span> cluster.<span class="hljs-built_in">name</span>=trivy<span class="hljs-operator">-</span>cluster
      <span class="hljs-operator">-</span> xpack.security.enabled=<span class="hljs-literal">false</span>
      <span class="hljs-operator">-</span> bootstrap.memory_lock=<span class="hljs-literal">true</span>
      <span class="hljs-operator">-</span> <span class="hljs-string">"ES_JAVA_OPTS=-Xms512m -Xmx512m"</span>
    ulimits:
      memlock:
        soft: <span class="hljs-number">-1</span>
        hard: <span class="hljs-number">-1</span>
    volumes:
      <span class="hljs-operator">-</span> es_data:<span class="hljs-operator">/</span>usr<span class="hljs-operator">/</span>share<span class="hljs-operator">/</span>elasticsearch<span class="hljs-operator">/</span>data
    ports:
      <span class="hljs-operator">-</span> <span class="hljs-string">"9200:9200"</span>
      <span class="hljs-operator">-</span> <span class="hljs-string">"9300:9300"</span>

  kibana:
    image: docker.elastic.co/kibana<span class="hljs-operator">/</span>kibana:<span class="hljs-number">7.17</span><span class="hljs-number">.9</span>
    container_name: kibana
    environment:
      <span class="hljs-operator">-</span> ELASTICSEARCH_HOSTS<span class="hljs-operator">=</span>http:<span class="hljs-comment">//elasticsearch:9200</span>
    ports:
      <span class="hljs-operator">-</span> <span class="hljs-string">"5601:5601"</span>
    depends_on:
      <span class="hljs-operator">-</span> elasticsearch

  logstash:
    image: docker.elastic.co/logstash<span class="hljs-operator">/</span>logstash:<span class="hljs-number">7.17</span><span class="hljs-number">.9</span>
    container_name: logstash
    volumes:
      <span class="hljs-operator">-</span> ./logstash<span class="hljs-operator">/</span>pipeline:<span class="hljs-operator">/</span>usr<span class="hljs-operator">/</span>share<span class="hljs-operator">/</span>logstash<span class="hljs-operator">/</span>pipeline
    environment:
      <span class="hljs-operator">-</span> LS_JAVA_OPTS<span class="hljs-operator">=</span><span class="hljs-string">"-Xmx256m -Xms256m"</span>
    ports:
      <span class="hljs-operator">-</span> <span class="hljs-string">"5044:5044"</span>
    depends_on:
      <span class="hljs-operator">-</span> elasticsearch

volumes:
  es_data:
    driver: local
</code></pre></li><li><p><strong>Configure Logstash Pipeline:</strong> Create the <code>pipeline</code> directory and <code>logstash.conf</code> file:</p><pre data-type="codeBlock" text="mkdir -p logstash/pipelinetouch logstash/pipeline/logstash.conf
"><code>mkdir <span class="hljs-operator">-</span>p logstash<span class="hljs-operator">/</span>pipelinetouch logstash<span class="hljs-operator">/</span>pipeline<span class="hljs-operator">/</span>logstash.conf
</code></pre><p>Add the following configuration to <code>logstash.conf</code>:</p><pre data-type="codeBlock" text="input {
  http {
    port =&gt; 5044
    codec =&gt; &quot;json&quot;
  }
}

filter {
  split {
    field =&gt; &quot;[Results]&quot;
  }
  split {
    field =&gt; &quot;[Results][Vulnerabilities]&quot;
  }
  mutate {
    rename =&gt; { &quot;[Results][Vulnerabilities][VulnerabilityID]&quot; =&gt; &quot;vulnerability_id&quot; }
    rename =&gt; { &quot;[Results][Vulnerabilities][PkgName]&quot; =&gt; &quot;package_name&quot; }
    rename =&gt; { &quot;[Results][Vulnerabilities][InstalledVersion]&quot; =&gt; &quot;installed_version&quot; }
    rename =&gt; { &quot;[Results][Vulnerabilities][FixedVersion]&quot; =&gt; &quot;fixed_version&quot; }
    rename =&gt; { &quot;[Results][Vulnerabilities][Severity]&quot; =&gt; &quot;severity&quot; }
    rename =&gt; { &quot;[Results][Vulnerabilities][Title]&quot; =&gt; &quot;title&quot; }
    rename =&gt; { &quot;[Results][Vulnerabilities][Description]&quot; =&gt; &quot;description&quot; }
    rename =&gt; { &quot;[Results][Vulnerabilities][References]&quot; =&gt; &quot;references&quot; }
    rename =&gt; { &quot;[Results][Type]&quot; =&gt; &quot;type&quot; }
  }
}

output {
  elasticsearch {
    hosts =&gt; [&quot;http://elasticsearch:9200&quot;]
    index =&gt; &quot;trivy-reports&quot;
    document_type =&gt; &quot;_doc&quot;
  }
  stdout { codec =&gt; rubydebug }
}
"><code>input {
  http {
    port <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-number">5044</span>
    codec <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"json"</span>
  }
}

filter {
  split {
    field <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"[Results]"</span>
  }
  split {
    field <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"[Results][Vulnerabilities]"</span>
  }
  mutate {
    rename <span class="hljs-operator">=</span><span class="hljs-operator">></span> { <span class="hljs-string">"[Results][Vulnerabilities][VulnerabilityID]"</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"vulnerability_id"</span> }
    rename <span class="hljs-operator">=</span><span class="hljs-operator">></span> { <span class="hljs-string">"[Results][Vulnerabilities][PkgName]"</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"package_name"</span> }
    rename <span class="hljs-operator">=</span><span class="hljs-operator">></span> { <span class="hljs-string">"[Results][Vulnerabilities][InstalledVersion]"</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"installed_version"</span> }
    rename <span class="hljs-operator">=</span><span class="hljs-operator">></span> { <span class="hljs-string">"[Results][Vulnerabilities][FixedVersion]"</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"fixed_version"</span> }
    rename <span class="hljs-operator">=</span><span class="hljs-operator">></span> { <span class="hljs-string">"[Results][Vulnerabilities][Severity]"</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"severity"</span> }
    rename <span class="hljs-operator">=</span><span class="hljs-operator">></span> { <span class="hljs-string">"[Results][Vulnerabilities][Title]"</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"title"</span> }
    rename <span class="hljs-operator">=</span><span class="hljs-operator">></span> { <span class="hljs-string">"[Results][Vulnerabilities][Description]"</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"description"</span> }
    rename <span class="hljs-operator">=</span><span class="hljs-operator">></span> { <span class="hljs-string">"[Results][Vulnerabilities][References]"</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"references"</span> }
    rename <span class="hljs-operator">=</span><span class="hljs-operator">></span> { <span class="hljs-string">"[Results][Type]"</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"type"</span> }
  }
}

output {
  elasticsearch {
    hosts <span class="hljs-operator">=</span><span class="hljs-operator">></span> [<span class="hljs-string">"http://elasticsearch:9200"</span>]
    index <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"trivy-reports"</span>
    document_type <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-string">"_doc"</span>
  }
  stdout { codec <span class="hljs-operator">=</span><span class="hljs-operator">></span> rubydebug }
}
</code></pre></li><li><p><strong>Start the Docker Containers:</strong> Run the Docker Compose setup:</p><pre data-type="codeBlock" text="docker-compose up -d
"><code>docker<span class="hljs-operator">-</span>compose up <span class="hljs-operator">-</span>d
</code></pre></li><li><p><strong>Send Trivy JSON Data to Logstash:</strong> You can use <code>curl</code> to send the Trivy JSON data to Logstash. Save your Trivy report to a JSON file (e.g., <code>trivy-report.json</code>), then use the following command to post the data:</p><pre data-type="codeBlock" text="curl -X POST &quot;http://localhost:5044&quot; -H &quot;Content-Type: application/json&quot; -d @trivy-report.json
"><code>curl <span class="hljs-operator">-</span>X POST <span class="hljs-string">"http://localhost:5044"</span> <span class="hljs-operator">-</span>H <span class="hljs-string">"Content-Type: application/json"</span> <span class="hljs-operator">-</span>d @trivy<span class="hljs-operator">-</span>report.json
</code></pre></li><li><p><strong>Access Kibana:</strong> Open Kibana in your web browser by navigating to <code>http://localhost:5601</code>. In Kibana, configure an index pattern to start visualizing your Trivy data.</p></li></ol><h3 id="h-example-of-kibana-index-pattern-configuration" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Example of Kibana Index Pattern Configuration</h3><ol><li><p>Go to <strong>Management</strong> &gt; <strong>Stack Management</strong> &gt; <strong>Index Patterns</strong> in Kibana.</p></li><li><p>Click <strong>Create Index Pattern</strong>.</p></li><li><p>Enter <code>trivy-reports</code> as the index pattern.</p></li><li><p>Configure the timestamp field if available, then click <strong>Create index pattern</strong>.</p></li></ol><h3 id="h-alternative-direct-ingestion-via-kibana-advanced" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Alternative: Direct Ingestion via Kibana (Advanced)</h3><p>If you prefer to use Kibana&apos;s Dev Tools for direct ingestion (not recommended for large data sets), follow these steps:</p><ol><li><p><strong>Convert Trivy JSON to NDJSON:</strong> Use a Python script (as previously discussed) to convert the JSON to NDJSON.</p></li><li><p><strong>Use Kibana Dev Tools:</strong> Open <strong>Dev Tools</strong> in Kibana and use the bulk API to ingest the NDJSON data.</p><pre data-type="codeBlock" text="POST _bulk
{ &quot;index&quot; : { &quot;_index&quot; : &quot;trivy-reports&quot;, &quot;_type&quot; : &quot;_doc&quot; } }
{ your_trivy_json_document }
"><code>POST _bulk
<span class="hljs-punctuation">{</span> <span class="hljs-attr">"index"</span> <span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span> <span class="hljs-attr">"_index"</span> <span class="hljs-punctuation">:</span> <span class="hljs-string">"trivy-reports"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"_type"</span> <span class="hljs-punctuation">:</span> <span class="hljs-string">"_doc"</span> <span class="hljs-punctuation">}</span> <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">{</span> your_trivy_json_document <span class="hljs-punctuation">}</span>
</code></pre></li></ol><p>This approach is more manual and not recommended for continuous ingestion. Using Logstash as an intermediary provides a more scalable and automated solution for handling Trivy reports and visualizing them in Kibana.</p>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
        <item>
            <title><![CDATA[Ворота в DeFi: платформа обменника с элементами Web3]]></title>
            <link>https://paragraph.com/@defi-in-security/defi-web3</link>
            <guid>5RiviILBOOIMJLbwqs4O</guid>
            <pubDate>Tue, 27 Sep 2022 16:49:02 GMT</pubDate>
            <description><![CDATA[@defisec July 12, 2022 Дополнение от 2022/08/24: добавлены п.6 и 7.Цель: пользователь напрямую за фиат покупает токены в нужном ему EVM-совместимом блокчейне подключаясь своим кошельком. За одно действие получает готовый к использованию в DeFi кошелёк, где раньше потребовалось бы использование шлюзов или централизованных бирж для обмена и последующего вывода в нужный блокчейн. Аналогичным образом облегчается и вывод из современных DeFi-приложений. Относительно материала про децентрализованный...]]></description>
            <content:encoded><![CDATA[<blockquote><p>@defisec July 12, 2022 Дополнение от 2022/08/24: добавлены п.6 и 7.</p></blockquote><p><strong><em>Цель</em></strong>: <em>пользователь напрямую за фиат покупает токены в нужном ему EVM-совместимом блокчейне подключаясь своим кошельком. За одно действие получает готовый к использованию в DeFi кошелёк, где раньше потребовалось бы использование шлюзов или централизованных бирж для обмена и последующего вывода в нужный блокчейн. Аналогичным образом облегчается и вывод из современных DeFi-приложений. Относительно материала про децентрализованный маркетплейс — здесь добавился второй пункт и удалились прочие, включая пункт про депозиторий. Если глубоко применить п.4 и п.5-6 про ДАО — проект можно считать относительно децентрализованным.</em></p><p><strong>Из указанных ниже ключевых особенностей обязательными являются первые две, третья крайне желательной, а остальные дополнительными.</strong></p><ol><li><p><strong>Авторизация на сайте и узнавание пользователя по кошельку</strong>. Пользователю достаточно иметь DApp-браузер с подключенным криптокошельком в нужной сети (баланс не обязателен) для проведения сделки или авторизации на сайте. Не нужну указывать ни почту, ни телефон, ни пароль -- сайт запоминает пользователя именно по его адресу кошелька блокчейна. Пример со стороны пользователя: Chrome+Metamask, TrustWallet и т.д. Пример со стороны платформ: любой актуальный DeX (PancakeSwap, Uniswap, Curve Finance и т.д.), блогинг-платформа mirror.xyz, автокомпаундер beefy.finance и прочие современные Web3-приложения, работающие на блокчейнах со смарт-контрактами.</p></li><li><p>Пользователь подключается и узнаётся сайтом своим кошельком (допустим в сети Polygon). Покупает криптовалюту в нужной ему сети (Polygon). Также имеет возможность поставить галочку, чтобы небольшую часть получить в токенах смарт-чейна для оплаты комиссии (Matic для Polygon). Дальше пользователь сразу может перейти на нужный ему проект DeFi и сразу начать его использовать без лишних действий. Поэтому и &quot;Ворота в DeFi&quot;.</p></li><li><p>Весь код всех смарт-контрактов и серверных приложений открыт и участвует в баг-баунти программах.</p></li><li><p>Для хостинга приложений и хранения пользовательской истории используются Web3-технологии: <strong>IPFS, Arweave, Filecoin</strong> или подобное. Управление этими ресурсами постепенно переводится на специальное ДАО или на админов на зарплате нанятых общим ДАО.</p></li><li><p><strong>ДАО</strong>. Всю эту схему можно делать с помощью ДАО или без. А можно запустить без ДАО, а ДАО запланировать. Как запустить ДАО-токен честно и прозрачно? Стартануть без ДАО, а за каждую сделку начислять токен управления (гавернанс токен), который и будет потом использоваться для голосования: принятия решений по смарт-контрактам напрямую или опосредованно через исполнительскую ДАО. Также можно сделать стейкинг этого токена, а с любой сделки брать минимальный процент (допустим 0.05%) , который и пойдёт в доход этого пула стейкинга. С помощью этого токена можно также голосовать по арбитрам и т.д. После этапа распределения можно прекратить раздачу токена за сделки, а можно оставить. А можно начать другой токен за сделки начислять -- вариантов много.</p></li><li><p><strong>Токеномика</strong>. Токеномика должна быть простой, понятной, действенной, настроенной на рост токена при росте популярности платформы, иметь утилитарность и функции гавернанс у токена. Это залог успеха. От двойных разных токенов мы сразу откажемся ввиду сложности как с точки зрения построения, с точки зрения просчёта результатов, так и с точки зрения понимания пользователем. Итак, токен TKN. Токен рейтинга. Токен ДАО. Токен с неограниченной эмиссией. 6.1) Первичный маркетинговый эирдроп для привлечения юзеров с других платформ. За подтверждённый рейтинг с другой топовой платформы P2P (BTC Banker, Binance P2P, etc.) начисляется определённое количество токенов. По результатам в оф. блоге в блокчейне (Mirror.xyz, Hive.blog) публикуется список, кто дал согласие на публичное подтверждение рейтинга. Пользователь по желанию может полностью показать исходный аккаунт с которого подтверждается рейтинг, либо просто с какой платформы, либо просто что рейтинг подтверждён, либо вообще отказаться от публичного обнародования результатов верифа рейтинга (но в блокчейне всё равно будет виден эирдроп аккаунту токена TKN). 6.2) Два токена TKN минтится при каждом вызове смарт-контракта на метод обмена и начисляется обеим сторонам обмена по токену. 6.3) Допустим, комиссия 0.1%, взимается у создателя объявления (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://bitzlato.com/ru/knowledgebase/bitzlatofees/">как в BTC Banker</a>): 0.09% идёт на выкуп токена TKN и помещение его в трежери, управляемый ДАО. Оставшиеся 0.01% идёт на действующую администрацию проекта (доп. опция: которая также может быть заменена с помощью ДАО). Таким образом, в момент сделки токен фактически платится в виде кешбека пользователю давая ему очки рейтинга. С другой стороны идёт выкуп с рынка токена и залочка его в трежери проекта, что создаёт давление на покупку на токен и стимулирует его рост. 6.4) Залочивая на выбранное время токен TKN и получая соответственный veTKN (vote escrowed TKN) в объёме, который зависит от времени залочки (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://curve.readthedocs.io/dao-vecrv.html">аналог veCRV Curve Finance</a>) — пользователь получает право голосовать по решениям ДАО. Таким как: управление трежери, размер комиссии, арбитры и прочее. При этмо рейтинг юзера не теряется, а в профиле отображается, что у юзера рейтинг на основе залоченного токена veTKN. Тикер для токена можно взять, например, P2p.</p></li><li><p><strong>Экспериментальные возможности.</strong> Мультисиг-архитектура депозитария. Продавец крипты делает депозит в мультисиг-аккаунт из двух ключей, первым ключом которого владеет сам продавец, а вторым — смарт-контракт платформы (с открытым кодом, верификацией и с аудитом). Соответственно, при обмене продавец имеет дополнительный рычаг отпуска-заморозки средств. Однако ничего не мешает проводить фиктивные сделки с самим собой. Тем не менее при каждой такой сделке происходит выкуп токена TKN согласно п.6.3</p></li></ol>]]></content:encoded>
            <author>defi-in-security@newsletter.paragraph.com (DeFi (in)security)</author>
        </item>
    </channel>
</rss>