<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pavel Odintsov on Medium]]></title>
        <description><![CDATA[Stories by Pavel Odintsov on Medium]]></description>
        <link>https://medium.com/@pavel.odintsov?source=rss-529f7312a4e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NtJIjUVHxdRo28Sh7Y8eaQ.jpeg</url>
            <title>Stories by Pavel Odintsov on Medium</title>
            <link>https://medium.com/@pavel.odintsov?source=rss-529f7312a4e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 21:52:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pavel.odintsov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[FastNetMon in search of perfect database for configuration and state storage]]></title>
            <link>https://medium.com/@pavel.odintsov/fastnetmon-in-search-of-perfect-database-for-configuration-and-state-storage-81abae5c7f89?source=rss-529f7312a4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/81abae5c7f89</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[ddos]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Pavel Odintsov]]></dc:creator>
            <pubDate>Tue, 28 Mar 2023 13:02:42 GMT</pubDate>
            <atom:updated>2023-03-28T13:14:20.790Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello! I’m <a href="https://www.linkedin.com/in/podintsov/">Pavel</a> and I’m CTO and co-founder of FastNetMon LTD, London, 🇬🇧. We’re cyber security software vendor and we develop <strong>DDoS</strong> 🎯 detection and mitigation <a href="https://fastnetmon.com/product-overview/">platform</a> for Telecoms.</p><p>Our 🏢 very first product was completely free open source on premise DDoS 🚨 detection platform called <a href="https://fastnetmon.com/install/">FastNetMon Community</a> and you can find it on <a href="https://github.com/pavel-odintsov/fastnetmon">GitHub</a>. It uses simple <a href="https://github.com/pavel-odintsov/fastnetmon/blob/master/src/fastnetmon.conf">text based</a> configuration file for configuration.</p><p>Example of FastNetMon Community configuration file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQU0CX_b-FFbVP_zTNhypw.png" /></figure><p>After great 🌟 feedback from Telecom and Cloud communities we started work on commercial edition called <a href="https://fastnetmon.com/product-overview/">FastNetMon Advanced</a> which introduced capabilities crucial for Terabit scale nationwide 🌏 networks such us scalability to millions of flows per second and lightning ⚡ fast DDoS detection.</p><p>To accommodate complex configurations of large networks we had to offer command line interface and API to store and alter product configuration.</p><p>In same time complexity of configuration was growing and we had such monstrosity 🤯 in text based configurations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGUTHrzwebw466djQeTMew.png" /></figure><p>That was time when we started looking on <strong>JSON</strong> for configuration 💾 storage format as it was the only way to accommodate complex configurations like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HL1Zjcl6skbg3mfgaJCRzg.png" /></figure><p>We agreed about data format but we had no persistent database which can store such data.</p><p>Why we actually need network 💽 database? Why not use embedded database like <a href="https://sqlite.org/index.html">SQLite</a> or even <a href="https://en.wikipedia.org/wiki/Lightning_Memory-Mapped_Database">LMDB</a>?</p><p>Let’s have a glance on FastNetMon Advanced design as it has multiple daemons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jypMVd6fyU_I4dccFTVJ4w.png" /></figure><p>You may notice that three different independent applications use database which is one left side with large M on it:</p><ul><li>fcli — command line management tool (Go) which offers human friendly way to manage configuration</li><li>API — which offers machine friendly way to manage configuration (Go)</li><li>FastNetMon — daemon implemented in C++ just reads configuration from database but may occasionally export some state into database. It’s core of our product, it does traffic processing and detects DDoS attacks</li></ul><p>We clearly need some way to implement read / write access to same data from multiple daemons and network database is a reasonable approach to implement it.</p><p>After doing initial research we ended up only with pretty small number of options to store 📜 JSON documents:</p><ul><li><a href="https://www.mongodb.com/">MongoDB</a></li><li><a href="https://rethinkdb.com/">RethinkDB</a></li><li><a href="https://couchdb.apache.org/">CouchDB</a></li></ul><p>Sadly RethinkDB was in process of <a href="https://rethinkdb.com/blog/rethinkdb-shutdown/">bankruptcy</a> and CouchDB was too heavy for our purpose and we ended up with using <a href="https://fastnetmon.com/docs-fnm-advanced/mongodb-integration-with-fastnetmon-advanced/">MongoDB</a> as our configuration database.</p><p>We did not consider any relational databases like <strong>MySQL</strong> of <strong>PostgreSQL</strong> because their JSON management capabilities were on early stages and we had no schema ⛔ policy in our product.</p><p>Sadly after MongoDB re-licensing under <a href="https://www.mongodb.com/community/licensing">SSPL</a> terms we started thinking about ways to replace MongoDB and it’s not easy to do.</p><p>What is the special about configuration databases in compare with regular use of databases? Configuration database is hidden deep inside of product and customer should not know about it’s existence until it fails.</p><p>We have 8 years of experience in operating MongoDB as configuration database with thousands of deployments worldwide 🗾 For all these years we faced multiple issues with MongoDB:</p><ul><li>It fails immediately when disk space runs out</li><li>Recent versions of MongoDB started requiring CPU <a href="https://pavel.network/please-do-not-require-avx-for-your-software/">capabilities</a> available only in latest CPU generations.</li><li>MongoDB is notoriously complicated to install with authorisation enabled as process of enabling authorisation is 3 step and involves</li><li>Upgrade process between multiple releases is a clear nightmare and full reinstall is the only option in many cases</li><li>Unusual licensing attracts too much attention as it requires involvement of lawyers for cases of cloud deployment</li><li>Many system administrators do not like MongoDB for variety of reasons</li><li>Lack of operational MongoDB experience in majority of companies</li><li>Modern MongoDB is not available in Debian, Ubuntu and Fedora due to licensing issues</li></ul><p>Recently we finished very successful <a href="https://fastnetmon.com/docs-fnm-advanced/using-fastnetmon-advanced-with-ferretdb-and-postgresql-instead-of-mongodb/">PoC</a> with FerretDB which provides the way to use PostgreSQL using MongoDB protocol and it looks as very good candidate for potential replacement of MongoDB in future.</p><p>And in same time <a href="https://rethinkdb.com/blog/community-update-stayin-alive">RethinkDB</a> is slowly getting back to live again.</p><p>I’ll be very happy to see more JSON native lightweight databases preferably implemented in Go or Rust as both of languages offer great cross platform support capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81abae5c7f89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[boost::unordered map is a new king of data structures]]></title>
            <link>https://medium.com/@pavel.odintsov/boost-unordered-map-is-a-new-king-of-data-structures-292124d3ee2?source=rss-529f7312a4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/292124d3ee2</guid>
            <category><![CDATA[hash]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Pavel Odintsov]]></dc:creator>
            <pubDate>Thu, 30 Jun 2022 14:17:48 GMT</pubDate>
            <atom:updated>2022-06-30T14:36:27.193Z</atom:updated>
            <content:encoded><![CDATA[<p>One lovely London morning I was wandering around social media and noticed some activity about new <a href="https://www.boost.org/doc/libs/develop/libs/unordered/doc/html/unordered.html">boost::unordered_map</a> which will be part of Boost 1.80 release.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*OoGvPL7Dk9QR6VGhX2Pq1A.png" /><figcaption>New bucket group layout used by boost::unordered_map 1.80</figcaption></figure><p>Why do I care? I’m CTO of <a href="https://github.com/pavel-odintsov/fastnetmon">FastNetMon</a> and we’re one of the <a href="https://fastnetmon.com/">fastest</a> products on market of DDoS detection and <a href="https://medium.com/@pavel.odintsov/data-structures-of-ddos-detection-a26880a01e4a">data structures</a> make us fast.</p><p>I was well aware that hash arrays are quite complicated data structures as I’ve been working with them for around decade in a latency critical environment of network traffic processing.</p><p>I was prepared but I did not expected that they’re that complicated before dealing with some internal implementation details. I would recommend reading this <a href="https://www.boost.org/doc/libs/develop/libs/unordered/doc/html/unordered.html">article</a> to get understating why boost::unordered_map is great.</p><p>Performance evaluation of hash arrays can be done with variety of ways. Initially we had quite <a href="https://github.com/pavel-odintsov/fastnetmon/blob/master/src/tests/traffic_structures_performance_tests.cpp#L83">dumb test</a> which filled hash array with sequence of 10m elements using 32 bit unsigned integers from 1 to 10m as keys and then tried to lookup them from 1 to 10m. Of course this test showed some numbers which can correlate with structure implementation but it had nothing to do with real lookup patterns of our application.</p><p>What is the proper way to test hash array? To test it properly you need to replicate your workload as close as possible.</p><p>In our case hash array keys are IPv4 addresses encoded as 32 bit unsigned big endian integers and value is a quite large 256 byte structure. What about lookup pattern? Can it be replicated in synthetic environment? Unfortunately, it will be very complicated as keys may be clustered and frequency of access to different keys will be very different. I’m pretty sure that it’s possible to build mathematical model to emulate this kind of distribution but it’s definitely above my level of mathematical education.</p><p>Let’s use traffic from real network. To run this data we’ve implemented <a href="https://github.com/pavel-odintsov/fastnetmon/blob/master/src/tests/traffic_structures_performance_tests_real_traffic.cpp#L112">new test</a> app which just loads list of keys into memory and then hammers data structure with them from memory.</p><p>What about our data set? Is it good? It has list of IP addresses which belong to one quite large ISP. It has 131k unique IP addresses and 180k entries in total. We’ve recorded this traffic as it arrived to collector to emulate real traffic behaviour with our test.</p><p>That’s time to run tests. We’be decided to run tests using Boost 1.78 (it was stable version in our product), 1.79 (current latest version) and 1.80 (to be released in coming weeks).</p><p>To run tests I used one of our labs which has AMD Ryzen 5 3600 6-Core Processor with Ubuntu 16.04 LTS and uses gcc 12.1 (latest stable version available).</p><p>I decided to run tests for std::map, std::unorderd_map and boost::unorderd_map only.</p><p><strong>Boost 1.78</strong></p><ul><li>std::map: 3.09965 Millions operations per second</li><li><strong>std::unordered_map</strong>: 25.374 Millions operations per second</li><li>boost::unordered_map: 19.9851 Millions operations per second</li></ul><p>It’s pretty expected that std::map is slowest here and results from boost::unordered_map is not that best and std::unordered_map is a clear winner.</p><p><strong>Boost 1.79</strong></p><ul><li>std::map: 3.00941 Millions operations per second</li><li><strong>std::unordered_map</strong>: 25.3469 Millions operations per second</li><li>boost::unordered_map: 15.9766 Millions operations per second</li></ul><p>There are no changes for std::map and std::unordered_map as we only upgraded Boost. But boost::unordered_map behaviour is quite curious as we can definitely see some slow down. According to library authors it may be related with switch to <a href="https://www.boost.org/users/history/version_1_79_0.html">Fibonacci</a> hashing.</p><p><strong>Boost 1.80</strong></p><ul><li>std::map: 3.01219 Millions operations per second</li><li>std::unordered_map: 25.2964 Millions operations per second</li><li><strong>boost::unordered_map</strong>: 32.3792 Millions operations per second</li></ul><p>Finally, we have winner. It’s very serious improvement since previous releases of Boost and new implementations beats std::unordered with whopping 20% performance gain.</p><p><strong>Conclusion</strong></p><p>Data structures are crucial part of high performance applications. std::unordered_map is a great data structure but if you outgrow it then boost::unordered_map will be your best choice after Boost 1.80 release.</p><p><strong>Thank you!</strong></p><p>I would like to say thank you to all authors of new boost::unordered map code Christian Mazakas, Joaquín M López Muñoz, Peter Dimov and all Boost contributors. It’s all made possible by effort funded by <a href="https://cppalliance.org/">C++ Alliance</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=292124d3ee2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data structures of DDoS detection]]></title>
            <link>https://medium.com/@pavel.odintsov/data-structures-of-ddos-detection-a26880a01e4a?source=rss-529f7312a4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a26880a01e4a</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[ddos]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Pavel Odintsov]]></dc:creator>
            <pubDate>Sun, 19 Jun 2022 18:07:44 GMT</pubDate>
            <atom:updated>2022-06-19T18:38:14.338Z</atom:updated>
            <content:encoded><![CDATA[<p>For quite long time DDoS detection and mitigation area was like magic with extremely limited access to information about algorithms used by such products. Almost all technologies were proprietary and their algorithms were patented. At <a href="https://github.com/pavel-odintsov/fastnetmon">FastNetMon</a> we do our best to explain all technical aspects behind DDoS detection logic.</p><p>I’ll cover one of the main data structures used by FastNetMon to detect attacks: hash maps (or tables).</p><p>To detect network attacks FastNetMon we need to count traffic (number of incoming / outgoing bytes / packets) for every single IPv4 (unsigned 32 bit integer key) or IPv6 (16 byte array) address in customer network. Networks may have from tens of thousands IPs up to tens of millions.</p><p>Data about traffic arrives as uneven stream which may include information about single network packet (exactly 1 packet with length up to 1500 bytes) or as aggregated flow (aggregation is implemented on network device side) which may include multiple packets and arbitrary length of so called flow for each IP address. Each time when we receive information about traffic we need to find existing record or create new for specific IP address and then increment byte and packet counters fields for it. You may find example in <a href="https://github.com/pavel-odintsov/fastnetmon/blob/43ae1c94a36a352809057c4624ecfd1197e4be72/src/fastnetmon_logic.cpp#L2698">FastNetMon Community code</a> at GitHub.</p><p>List of IPs actually owned by ISP in any particular network is stable enough and we will see new IPs only after tool restart (aka warm up period). After few minutes we expected extremely small number of new IPs. So we mostly care about lookup performance. We do not remove elements unless we reach scalability limitations of unordered_map.</p><p>We call this logic host traffic accumulators. As hash map value we use pretty <a href="https://github.com/pavel-odintsov/fastnetmon/blob/43ae1c94a36a352809057c4624ecfd1197e4be72/src/map_element.hpp#L11">large structure</a> around 200 plus bytes.</p><p>So we have total number of packets / bytes in incoming / outgoing directions in our hash map. For purpose of attack detection we need to calculate speed per second for each host. We use different algorithms but most common one is just average calculated every single second. We scan all keys in hash map and then export them to another structure and then set set every element in our traffic accumulator hash to zeroes.</p><p>So we’re both interested in element lookup time and full iteration time (aka full scan). We have no requirement about stable address for node or any other artificial standard driven constrains from STL. For most of the counters we rely on std::unordered map from C++ 20 STL library.</p><p>Unfortunately, it does not work that great as we expect as insert time is far away from our expectations. Even worse that hash table seriously degrades after crossing around half million of keys.</p><p>That’s a reason why we’re in constant search for new hash tables which can perform better for our workload. We maintain hash table <a href="https://github.com/pavel-odintsov/fastnetmon/blob/master/src/tests/traffic_structures_performance_tests.cpp">performance test</a> as part of our test suite and you can find some measurements <a href="https://github.com/pavel-odintsov/fastnetmon/wiki/Traffic-Counters-Structures-performance-evaluation">here</a>.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a26880a01e4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[B2B sanction compliance for global companies]]></title>
            <link>https://medium.com/@pavel.odintsov/b2b-sanction-compliance-for-global-companies-e7ab64c2ba3f?source=rss-529f7312a4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7ab64c2ba3f</guid>
            <category><![CDATA[b2b]]></category>
            <category><![CDATA[sanctions]]></category>
            <category><![CDATA[compliance]]></category>
            <category><![CDATA[kyc]]></category>
            <category><![CDATA[aml]]></category>
            <dc:creator><![CDATA[Pavel Odintsov]]></dc:creator>
            <pubDate>Thu, 03 Mar 2022 21:24:48 GMT</pubDate>
            <atom:updated>2022-03-03T21:55:32.187Z</atom:updated>
            <content:encoded><![CDATA[<p>During the last unprecedented week we saw an enormous number of sanctions targeted against many companies and individuals.</p><p>I would like to highlight the importance of sanctions. Western governments put them for very serious reasons and we should not treat them as a bureaucratic burden and ignore them.</p><p>I have 8 years of experience as a technical member of a team responsible for fraud checking and compliance for EU and UK based companies working in the <a href="https://en.wikipedia.org/wiki/Business-to-business">B2B</a> market.</p><p>There are many products which may help you to implement <a href="https://en.wikipedia.org/wiki/Know_your_customer">KYC</a> and <a href="https://en.wikipedia.org/wiki/Money_laundering#Combating">AML</a> for individuals but the same instruments for the B2B sector are very basic or cover only a small subset of countries.</p><p>Does it mean that they should rely on such weak instruments? No, it’s extremely irresponsible and very risky for your business. Having strong procedures to comply with sanctions regulations will help you to reduce the amount of fraud and reduce possible risk from financial institutions such as banks and payment operators.</p><p>All recommendations from this article are subject to data protection policies such as <a href="https://en.wikipedia.org/wiki/General_Data_Protection_Regulation">GDPR</a> in your country.</p><p>For accounting and taxations reasons we will need some basic information which :</p><ul><li>Company’s name</li><li>Company’s jurisdiction (i.e. country where company is registered)</li><li>Company’s physical address</li><li>Company’s phone number</li><li>Company’s payment credentials</li><li>Tax identifier (such as <a href="https://en.wikipedia.org/wiki/Value-added_tax">VAT</a>)</li><li>Contact email (on corporate domain)</li><li>Contact person credentials</li><li>IP from which order was placed</li></ul><p>Such information is crucial and cannot be skipped in any way in a large number of countries.</p><p>What can we do with all such information? We can do lots of things.</p><h3>Company name, site and tax identifiers</h3><p>I can recommend starting from simple checking of their site and checking for any references to it in Google, some basic query “Company name” will show you plenty of information.</p><p>Of course you need to have some expectations specific for your type of industry. So you do not expect that some abstract “international import export company” will buy high precision optics from you, right? So be cautious and check.</p><p>Is it a genuine company? What does it mean? It means that anybody from the Internet can use the credentials of another company and pretend to be from it. For individuals we can request a passport and photo to match them but it’s very tricky to implement for companies.</p><p>That’s how complications start.</p><p>Many countries keep their company registries open. For example it the UK you can find information about any company using this interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oCpXKEPSGld0bh7E" /></figure><p>Lots of information here and all of it is very useful to make decisions about a company. Section about people is the most interesting as sanctions may be against their owners.</p><p>Unfortunately, many countries do not offer such information or offer it for a small fee. To find them I can recommend using queries as “companies or business registry &lt;country name&gt;”. In non English languages it may be tricky but you can find some English references or hints about it. Typically, the fee is pretty small and the company can afford to spend it to know more about the customer.</p><p>In many cases you can find the same information indexed by Google using Google query by company full name, their TAX code or company’s number.</p><p>So at this point we have a pretty good overview of the company or we failed to find any information. Ask them!</p><p>Talking with your customer and asking for documents is actually one of the most efficient ways to get feeling that something is wrong. It’s a pretty common procedure and all people in procurement departments have such documents in place.</p><p>What kind of documents do you need to ask?</p><ul><li>Company’s registration certificate</li><li>Company’s tax jurisdiction (i.e. VAT allocation certificate)</li></ul><p>Of course these documents may be doctored or downloaded from the Internet. I can recommend doing cross checking using public company’s registries. Many countries (EU, UK and many others) offer instruments to check the correctness of tax identifiers. For example, EU’s tax identifier validation <a href="https://ec.europa.eu/taxation_customs/vies/">tool</a> offers very detailed information about company.</p><p>Look on example query for <a href="https://www.veriff.com/">Veriff’s</a> VAT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N8MZYb-AKa4gWK7w" /></figure><p>Again, use Google to find mentions of their tax id. Guess query? Something like: “Company name VAT XXXYYYZZZ”. There is a very common obligation to publish tax identifiers on company sites.</p><p>At this point we have a pretty good understanding of the company and have their tax identifiers. Should we stop here? No. Even if you see that the company looks legitimate and operates from sanctions free jurisdiction it may be a so-called shell company whose only purpose is to pay for some services on behalf of the main entity which is under sanctions.</p><h3>Checking individuals behind company</h3><p>How can we find it? Let’s move to individuals who work for a company and who manage this company. Our best friend here is LinkedIN. It’s not a silver bullet as it’s not very popular in some countries or it may even be banned by the government in some countries.</p><p>Searching on Linkedin or Google using the query “person name + company name” can show you plenty of information.</p><p>In some cases you may find more different companies founded / owned / managed by the same people and that’s how you can find something unusual in their activity.</p><p>Some registries allow you to search by person name and find all companies affiliated with that person. So we can use the person’s name itself to check against the sanctions list and then we can use retrieved information to understand a company’s ties with a specific country.</p><p>We expect that in coming weeks and months you may see plenty of companies created only for the purpose to bypass sanctions and such fresh companies must alert you.</p><h3>Company address</h3><p>Check the company’s address on Google Maps. It will provide enough background to understand that such a place just cannot be the office of a respectable company. Well, I agree that pandemic changed landscape and pushed hard for remote work but it still applies to many companies.</p><h3>Phone</h3><p>Next target is the phone. There are plenty of tools which can be used to verify that a customer actually has access to phone specified in order details. Even if you do not talk with customers we recommend using some tools like those provided by <a href="https://www.twilio.com/">Twilio</a> to verify that customers have access to numbers. <a href="https://www.twilio.com/">Twilio</a> provides enough information about a number’s type (i.e. landline or mobile) and it can be used to check that a customer actually has a direct to phone network in a specific country. Best option to call customer and involve customer in some basic conversation and try to find some strange patterns in their behavior.</p><p>What is the best topic to ask? Try to learn how they’re going to use your product or service. It’s very important information for your company which may be used heavily by marketing, sales and product development.</p><h3>Payment credentials</h3><p>There are plenty of options to pay for services in B2B area and I would like to mention some of them:</p><ul><li>International bank transfer, so called <a href="https://en.wikipedia.org/wiki/SWIFT">SWIFT</a></li><li>Local bank transfer</li><li>Credit card</li><li>PayPal</li><li><a href="https://en.wikipedia.org/wiki/Automated_clearing_house">ACH</a> / <a href="https://en.wikipedia.org/wiki/Direct_debit">Direct debit</a></li></ul><p>You may hear about ACH or direct debit for the first time. It’s actually a very convenient payment option when your customer provides their consent and their bank credentials and you just collect money from their balance. Looks nice and you have plenty of information about the customer’s bank and it can be used to decide that it looks legit.</p><p>Is it an actual bank at all? There are so many companies on the market which have no proper bank license and they provide so called electronic money wallets which can be used by companies.</p><p>I’m not saying that these services are bad but typically they have weakier KYC and AML procedures and they’re pretty popular among customers trying to bypass sanctions.</p><p>It’s pretty expected that a bank should be in the same country as the company. It’s not completely right for large companies but you probably know large companies by name and you will have no issues with making conclusions that they’re legitimate.</p><p><a href="https://www.paypal.com/">PayPal</a> offers some visibility about the payer’s name and email. So you need to check that this email uses a corporate domain. Having a corporate PayPal account on gmail.com is not something you expect.</p><p>It’s a very common scenario when a company from one jurisdiction which cannot pay directly for some reasons may use a payment instrument which belongs to an individual in another country and you need to stay alert.</p><p>The most popular payment method even for business customers is credit card and you can get lots of information from your payment provider. My own credit card processor of choice is <a href="https://stripe.com/gb">Stripe</a>. I love them and their products.</p><p>They offer a nice instrument called “Radar for Fraud Teams” which offers great tool to completely ban credit cards issued by specific countries. It’s extremely simple and will save you from such significant financial risk with one option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s3bUfRoWAva-J35q" /></figure><p>You can add as many countries as you can. In addition Stripe can show information about country and bank which issued credit card in transactions list. Again, check that credit card was issues by real bank in same country instead of some “electronic money wallet”.</p><h3>IP addresses</h3><p>The very last resort to confirm that customer is fine or not is their IP address. Do you expect that customer should use some residential ISP near their office or at least in the same country? Pretty expected. <a href="https://www.maxmind.com/en/home">MaxMind</a> offers great instruments to identify <a href="https://en.wikipedia.org/wiki/VPN_service">VPNs</a>, proxies and risky IP addresses and I recommend integrating.</p><p>You can do it even simpler by using a tool called <a href="https://en.wikipedia.org/wiki/WHOIS">whois</a>. Just use “whois IP” and then you will see information in format like this:</p><blockquote>OrgName: DigitalOcean, LLC<br>OrgId: DO-13<br>Address: 101 Ave of the Americas<br>Address: 10th Floor<br>City: New York<br>StateProv: NY<br>PostalCode: 10013<br>Country: US</blockquote><p>Well, for legitimate customers which do not use VPN you can see something about their region or country here but not abstract cloud providers.</p><h3>Conclusions</h3><p>We’ve covered very basic steps which are absolutely crucial for checking customers against the sanctions list but of course they’re not enough. It’s a constantly changing area with new approaches emerging on a weekly and monthly basis. Stay alert and share your experience with global business community.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7ab64c2ba3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making 35 000 000 IP lookup operations per second with Patricia tree]]></title>
            <link>https://medium.com/@pavel.odintsov/making-35-000-000-ip-lookup-operations-per-second-with-patricia-tree-83e884ee2d15?source=rss-529f7312a4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/83e884ee2d15</guid>
            <category><![CDATA[prefix]]></category>
            <category><![CDATA[particia]]></category>
            <category><![CDATA[network]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[radix]]></category>
            <dc:creator><![CDATA[Pavel Odintsov]]></dc:creator>
            <pubDate>Sun, 20 Feb 2022 21:22:23 GMT</pubDate>
            <atom:updated>2022-02-20T21:53:36.891Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I’ll try to make some performance evaluation of <a href="https://en.wikipedia.org/wiki/Radix_tree#Variants">Patricia</a> tree for purpose of IP address lookup in list of prefixes in C and C++ languages.</p><p>Briefly, Patricia tree can help us to confirm that IP address 10.0.0.1 belongs or not to list of networks: 10.0.0.0/24, 10.1.1.0/22 and 10.2.4.0/32.</p><figure><img alt="IP address lookup" src="https://cdn-images-1.medium.com/max/1024/1*EUy9DB_Yj6H-Tkq3EI5bFw.jpeg" /></figure><h4>Naive implementation of IP lookup</h4><p>We may try to do linear search and it may be fast enough when we have some reasonable number of prefixes which can fit in CPU cache. Maybe it will work fine until you have 20–30 prefixes. In real world scenarios we have hundreds of prefixes with different lengths and linear search will not scale well as we will need to check every single prefix in list and time complexity will be as bad as O(n).</p><p>It may get even more complicated if we have need to implement <a href="https://en.wikipedia.org/wiki/Longest_prefix_match"><em>longest prefix match</em></a> query. What is this? For example, you may have IP address 10.0.0.1 and you have two prefixes in list which both contain it 10.0.0.0/8 and 10.0.0.0/24. For many network and business applications you may need to select longest (24 is longer than 8).</p><p>For example we offer our customers ability to set different traffic levels for DDoS detection on prefix basis. So you may set some generic threshold for 10.0.0.0/8 but you know that network 10.0.0.0/24 has heavy loaded services you may set bigger values for it. During attack detection <a href="https://fastnetmon.com/">FastNetMon</a> will use custom configuration for this specific /24 because we use longest prefix match to retrieve configuration.</p><h4>What is Patricia tree?</h4><p>It’s type of Radix tree which was introduced around 2005 in <a href="http://web.archive.org/web/20050512074219/http://www.mrtd.net/">MRT</a> aka Multi-threaded Routing Toolkit. It’s pretty old but it’s very mature and battle tested.</p><p>In <a href="https://github.com/pavel-odintsov/fastnetmon">FastNetMon</a> DDoS Detection toolkit we use Patricia tree for two cases:</p><ul><li>To detect packet or flow direction: incoming or outgoing (belong or not belong check against list of prefixes operated by company)</li><li>To find hostgroup which has configuration for specific IP address (<a href="https://en.wikipedia.org/wiki/Longest_prefix_match">longest prefix match</a>)</li></ul><p>As <a href="https://fastnetmon.com/">FastNetMon</a> operates on really large networks and analyses many terabits of capacity we need to understand what are our expectation about IP lookup performance from Patricia.</p><p><strong>Performance evaluation scenario</strong></p><p>Patricia tree is a tree and it performance heavily depends on prefix lengths and their number. Having few /8 and thousands of /32 in list will show extremely different results. How can we test it? We decided to retrieve prefixes from real very large network which contains around 380 prefixes of length ranging from /22 to /15. Most popular prefix length in our data set was /16.</p><p>To test performance of tree lookup we need to lookup something. We can generate random IP addresses for lookup but it will not reflect real nature of networks because we have different performance for miss in tree and hit in tree. Both miss and hit may happen on different levels of tree and it will lead to different performance.</p><p>To get performance test result which are as possible close to our real workloads we need to retrieve some real traffic from network and we managed to do it. In our real traffic sample we had 300k+ pairs of source and destination IP addresses.</p><p>For our tests we used our own <a href="https://github.com/pavel-odintsov/fastnetmon/blob/master/src/libpatricia/patricia.c">copy</a> of Patricia tree and we used this <a href="https://gist.github.com/pavel-odintsov/22f9bc22aa0728e4b7e8327cc3438a49">app</a> to load prefixes into tree and blast it with real traffic stored in JSON file. Our implementation is single threaded.</p><p>To get precise results we load source traffic into continuous memory region (pre-allocated std::vector) and run lookup operation patricia_search_best2(lookup_tree, &amp;prefix, 1) on each source and destination IPs from input data set. And then we repeat last step 100000 times.</p><p>After running test app for more than half hour we got following results:</p><blockquote>./patricia_performance_tests <br>Total time is 1781 seconds total ops: 1116028928<br>Million of ops per second: 17.5</blockquote><p>As each iteration does one lookup for source IP and another one for destination IP we need to multiply 17.5 by two. Finally we got really great performance of 35 000 000 lookup / s which is more than enough for many applications.</p><h4>Test server configuration</h4><p>AMD Ryzen 7 5800X 8-Core Processor, 16 logical CPU cores, 32 GB DDR4 3000 Mhz, B450 TOMAHAWK, Noctua NH-D15.</p><h4>Conclusions</h4><p>35 000 000 IP lookup per second is really nice result for 16 year old library and pretty old algorithm. Such performance covers most of our needs for 10G bandwidth but we still need to use alternative approaches to improve performance for 40G and 100G cases. As good direction of research in this field I can point you towards DIR-24–8 and DXR algorithms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83e884ee2d15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Capturing Packets in Linux at a Speed of Millions of Packets per Second without Using Third Party…]]></title>
            <link>https://medium.com/@pavel.odintsov/capturing-packets-in-linux-at-a-speed-of-millions-of-packets-per-second-without-using-third-party-ef782fe8959d?source=rss-529f7312a4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef782fe8959d</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[traffic]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Pavel Odintsov]]></dc:creator>
            <pubDate>Sun, 20 Feb 2022 17:40:29 GMT</pubDate>
            <atom:updated>2022-02-20T17:40:29.381Z</atom:updated>
            <content:encoded><![CDATA[<h3>Capturing Packets in Linux at a Speed of Millions of Packets per Second without Using Third Party Libraries</h3><p>My article will tell you how to receive 10 million packets per second without using any third party libraries such as Netmap, PF_RING, DPDK and others.</p><p>We will do this using the usual Linux kernel version 3.16 and a certain amount of code in C and C ++.</p><p>This article was published at 25th of June 2015. I published it here because original web site ceased to exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmP8ZPUiBZItgaoh4oEVVw.jpeg" /></figure><p>As introduction I’d like to share a few words about how pcap, the well-known way of capturing packets, works. It is used in such popular utilities as iftop, tcpdump, arpwatch.</p><p>To start you open interface using pcap and wait for packets from it using the usual bind / recv approach. The kernel, in turn, receives data from the network card and stores it in the kernel space, after that it detects that the user wants to receive it in the user space and passes through the recv command argument, the address of the buffer where to put this data. The kernel copies the data (for the second time).</p><p>In addition, remember that recv is a system call and we call it for every packet coming to the interface, system calls are usually very fast, but the speed of modern 10GE interfaces (up to 14.6 million calls per second) leads to the fact that even a light call becomes very costly to the system solely because of the frequency of the calls.</p><p>It is also worth noting that we usually have more than 2 logical cores on our server. And the data can arrive to any of them. And an application that receives data using pcap uses one core. Here we turn on locks on the kernel side and drastically slow down the capture process — now we are not only copying memory / processing packets, but waiting for the release of locks occupied by other cores. In worst cases locks can often take up to 90% of the processor resources of the entire server.</p><p>Good list of problems? Yep and we will try to solve them all.</p><p>In this article we will be working on mirror ports (which means that from network switch we receive a copy of all the traffic of a certain server). On the server side we observe SYN flood packets of the minimum size at a speed of 14.6 mpps / 7.6GE.</p><p>We will use Intel 82599 NIC with ixgbe drivers from SourceForge 4.1.1, Debian 8 Jessie. Module configuration: <em>modprobe ixgbe RSS=8,8</em>. I have an Intel i7 3820 processor with 8 logical cores.</p><h4>Distribute interrupts across available cores</h4><p>I draw your attention to the fact that packets arrive on the port, the target MAC addresses of which do not match the MAC address of our network card.</p><p>Otherwise, the Linux TCP/IP stack will kick in and the machine will choke on traffic. This point is very important, we are now discussing only the capture of other people’s traffic, and not the processing of traffic that is intended for this machine (although my method is suitable for this case too).</p><p>Now let’s check how much traffic we can accept if we start listening to all traffic.</p><p>Enable promisc mode on the network card: <em>ifconfig eth6 promisc</em></p><p>After that, in htop we will see a very unpleasant picture — a complete overload of one of the cores:</p><pre>1 [||||||||||||||||||||||||||||||||||||||||||||||||||||||||||100.0%]     <br>2 [                                                           0.0%]     <br>3 [                                                           0.0%]     <br>4 [                                                           0.0%]     <br>5 [                                                           0.0%]<br>6 [                                                           0.0%]<br>7 [                                                           0.0%]<br>8 [                                                           0.0%]</pre><p>To determine the packet speed on the interface, we will use the special script <a href="https://gist.github.com/pavel-odintsov/bc287860335e872db9a5">pps.sh</a>. At the same time, the speed on the interface is quite small — 4 million packets per second:</p><pre>RX eth6: 3 882 721 pkts/s<br>RX eth6: 3 745 027 pkts/s</pre><p>To solve this problem and distribute the load across all logical cores (I have 8 of them), you need to run the following <a href="http://gist.github.com/pavel-odintsov/9b065f96900da40c5301">script</a> which will distribute interrupts from all 8 queues of the network card to all available logical cores.</p><p>Great, the speed immediately flew up to 12mpps (but this is not a capture, this is just an indicator that we can read traffic at this speed from the network)</p><pre>TX eth6: 0 pkts/s RX eth6: 12 528 942 pkts/s<br>TX eth6: 0 pkts/s RX eth6: 12 491 898 pkts/s<br>TX eth6: 0 pkts/s RX eth6: 12 554 312 pkts/s</pre><p>And the load on the cores has stabilized:</p><pre>1  [|||||                                                      7.4%]     <br>2 [|||||||                                                     9.7%]     <br>3  [||||||                                                     8.9%]    <br>4  [||                                                         2.8%]     <br>5  [|||                                                        4.1%]<br>6  [|||                                                        3.9%]<br>7  [|||                                                        4.1%]<br>8  [|||||                                                      7.8%]</pre><p>I will use two code examples in this article and you can find them here: AF_PACKET, AF_PACKET + FANOUT: <a href="https://gist.github.com/pavel-odintsov/c2154f7799325aed46ae">code</a>, AF_PACKET RX_RING, AF_PACKET + RX_RING + FANOUT: <a href="https://gist.github.com/pavel-odintsov/15b7435e484134650f20">code</a>.</p><p>These are complete applications with the maximum level of optimizations. I do not provide intermediate (obviously slower versions of the code) — but all the flags for managing all optimizations are selected and declared in the code as bool — you can easily repeat my path for yourself.</p><h4>First attempt to run AF_PACKET capture without optimizations</h4><p>So, we launch the application for capturing traffic using AF_PACKET:</p><pre>We process: 222 048 pps<br>We process: 186 315 pps</pre><p>And we can see that all CPUs cores are on peak load:</p><pre>1 [||||||||||||||||||||||||||||||||||||||||||||||||||||||||  86.1%]     <br>2 [||||||||||||||||||||||||||||||||||||||||||||||||||||||    84.1%]     <br>3 [||||||||||||||||||||||||||||||||||||||||||||||||||||      79.8%]     <br>4 [||||||||||||||||||||||||||||||||||||||||||||||||||||||||| 88.3%]     <br>5 [|||||||||||||||||||||||||||||||||||||||||||||||||||||||   83.7%]<br>6 [||||||||||||||||||||||||||||||||||||||||||||||||||||||||| 86.7%]<br>7 [||||||||||||||||||||||||||||||||||||||||||||||||||||||||||89.8%]<br>8 [|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||90.9%]</pre><p>The reason that the kernel drowned in locks, on which it spends all the processor time:</p><pre>Samples: 303K of event &#39;cpu-clock&#39;, Event count (approx.): 53015222600<br>  59.57%  [kernel]        [k] _raw_spin_lock<br>   9.13%  [kernel]        [k] packet_rcv<br>   7.23%  [ixgbe]         [k] ixgbe_clean_rx_irq<br>   3.35%  [kernel]        [k] pvclock_clocksource_read<br>   2.76%  [kernel]        [k] __netif_receive_skb_core<br>   2.00%  [kernel]        [k] dev_gro_receive<br>   1.98%  [kernel]        [k] consume_skb<br>   1.94%  [kernel]        [k] build_skb<br>   1.42%  [kernel]        [k] kmem_cache_alloc<br>   1.39%  [kernel]        [k] kmem_cache_free<br>   0.93%  [kernel]        [k] inet_gro_receive<br>   0.89%  [kernel]        [k] __netdev_alloc_frag<br>   0.79%  [kernel]        [k] tcp_gro_receive</pre><h4>Optimizing AF_PACKET capture with FANOUT</h4><p>So what to do? We know that locks occur when multiple processors try to use the same resource. In our case, this is due to the fact that we have one socket and one application consumes it, which forces the other 8 logical processors to stand in constant waiting.</p><p>Here a great function will come to our aid — FANOUT. For AF_PACKET, we can run several. The most optimal in our case will be the number of processes equal to the number of logical cores.</p><p>In addition, we can set the algorithm by which data will be distributed over these sockets. I chose the <em>PACKET_FANOUT_CPU</em> mode, since in my case the data is very evenly distributed among the queues of the network card and this, in my opinion, is the least resource-intensive balancing option (although I can’t vouch for it — I recommend looking in the kernel code).</p><p>We correct in the code example bool use_multiple_fanout_processes = true;</p><p>And start the application again. O miracle, we got breathtaking 10x acceleration:</p><pre>We process: 2 250 709 pps<br>We process: 2 234 301 pps<br>We process: 2 266 138 pps</pre><p>Processors, of course, are still fully loaded:</p><pre>1 [|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||92.6%]     <br>2 [|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||93.1%]     <br>3 [|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||93.2%]     <br>4 [|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||93.3%]     <br>5 [|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||93.1%]<br>6 [|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||93.7%]<br>7 [|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||93.7%]<br>8 [|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||93.2%]</pre><p>But the perf top map looks completely different — there are no more locks:</p><pre>Samples: 1M of event &#39;cpu-clock&#39;, Event count (approx.): 110166379815<br>  17.22%  [ixgbe]         [k] ixgbe_clean_rx_irq      <br>   7.07%  [kernel]        [k] pvclock_clocksource_read          <br>   6.04%  [kernel]        [k] __netif_receive_skb_core    <br>   4.88%  [kernel]        [k] build_skb     <br>   4.76%  [kernel]        [k] dev_gro_receive    <br>   4.28%  [kernel]        [k] kmem_cache_free <br>   3.95%  [kernel]        [k] kmem_cache_alloc <br>   3.04%  [kernel]        [k] packet_rcv <br>   2.47%  [kernel]        [k] __netdev_alloc_frag <br>   2.39%  [kernel]        [k] inet_gro_receive<br>   2.29%  [kernel]        [k] copy_user_generic_string<br>   2.11%  [kernel]        [k] tcp_gro_receive<br>   2.03%  [kernel]        [k] _raw_spin_unlock_irqrestore</pre><h4>Optimizing AF_PACKET Capture with RX_RING — Ring Buffer</h4><p>What to do and why is it still slow? The answer is in the build_skb function, which means that two memory copies are still being made inside the kernel.</p><p>Now let’s try to deal with memory allocation through the use of RX_RING. Look on results, we’re nearing 4 MPPS:</p><pre>We process: 3 582 498 pps<br>We process: 3 757 254 pps<br>We process: 3 669 876 pps</pre><p>Such a speed increase was ensured by the fact that memory is now copied from the network card buffer only once. And when passing from kernel space to user space, there is no copy process too. This is provided by a shared buffer allocated in the kernel and skipped to user space.</p><p>The approach to work also changes — now we can’t hang and listen when a packet arrives (remember — this is an overhead), Now using the poll call we can wait for a signal when the whole block is filled. And then start processing it.</p><h4>AF_PACKET capture optimization with RX_RING by FANOUT</h4><p>But still we have problems with blocking. How to defeat them? The old method is to turn on FANOUT and allocate a block of memory for each handler thread.</p><pre>Samples: 778K of event &#39;cpu-clock&#39;, Event count (approx.): 87039903833<br>  74.26%  [kernel]       [k] _raw_spin_lock<br>   4.55%  [ixgbe]        [k] ixgbe_clean_rx_irq<br>   3.18%  [kernel]       [k] tpacket_rcv<br>   2.50%  [kernel]       [k] pvclock_clocksource_read<br>   1.78%  [kernel]       [k] __netif_receive_skb_core<br>   1.55%  [kernel]       [k] sock_def_readable<br>   1.20%  [kernel]       [k] build_skb<br>   1.19%  [kernel]       [k] dev_gro_receive<br>   0.95%  [kernel]       [k] kmem_cache_free<br>   0.93%  [kernel]       [k] kmem_cache_alloc<br>   0.60%  [kernel]       [k] inet_gro_receive<br>   0.57%  [kernel]       [k] kfree_skb<br>   0.52%  [kernel]       [k] tcp_gro_receive<br>   0.52%  [kernel]       [k] __netdev_alloc_frag</pre><p>So, we connect the FANOUT mode for the RX_RING version:</p><p>Wow, we got breathtaking 9 MPPS:</p><pre>We process: 9611580 pps<br>We process: 8912556 pps<br>We process: 8941682 pps<br>We process: 8854304 pps</pre><p>per top:</p><pre>Samples: 224K of event &#39;cpu-clock&#39;, Event count (approx.): 42501395417<br>  21.79%  [ixgbe]              [k] ixgbe_clean_rx_irq<br>   9.96%  [kernel]             [k] tpacket_rcv<br>   6.58%  [kernel]             [k] pvclock_clocksource_read<br>   5.88%  [kernel]             [k] __netif_receive_skb_core<br>   4.99%  [kernel]             [k] memcpy<br>   4.91%  [kernel]             [k] dev_gro_receive<br>   4.55%  [kernel]             [k] build_skb<br>   3.10%  [kernel]             [k] kmem_cache_alloc<br>   3.09%  [kernel]             [k] kmem_cache_free<br>   2.63%  [kernel]             [k] prb_fill_curr_block.isra.57</pre><p>Even more interesting that we reduced load on CPUs little bit:</p><pre>1  [|||||||||||||||||||||||||||||||||||||                     55.1%]     <br>2  [|||||||||||||||||||||||||||||||||||                       52.5%]     <br>3  [||||||||||||||||||||||||||||||||||||||||||                62.5%]     <br>4  [||||||||||||||||||||||||||||||||||||||||||                62.5%]     <br>5  [|||||||||||||||||||||||||||||||||||||||                   57.7%]<br>6  [||||||||||||||||||||||||||||||||                          47.7%]<br>7  [|||||||||||||||||||||||||||||||||||||||                   55.9%]<br>8  [|||||||||||||||||||||||||||||||||||||||||                 61.4%]</pre><p>In conclusion, I would like to add that Linux is simply an amazing platform for analyzing traffic, even in an environment where it is impossible to build any specialized kernel module. This is very, very pleasing. There is hope that in the next kernel versions it will be possible to process 10GE at a full wire-speed of 14.6 million/packets of a second using a 1800 megahertz processor.</p><p>Recommended reading materials:</p><ul><li>man <a href="https://www.kernel.org/doc/Documentation/networking/packet_mmap.txt">page</a> about packet mmap.</li><li>map <a href="http://man7.org/linux/man-pages/man7/packet.7.html">page</a> about packet interface</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef782fe8959d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[For more than 4 years I have been working exclusively with the DNS protocol and during this time I…]]></title>
            <link>https://medium.com/@pavel.odintsov/for-more-than-4-years-i-have-been-working-exclusively-with-the-dns-protocol-and-during-this-time-i-9f7229564a3c?source=rss-529f7312a4e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f7229564a3c</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Pavel Odintsov]]></dc:creator>
            <pubDate>Tue, 25 Aug 2020 19:58:29 GMT</pubDate>
            <atom:updated>2020-08-25T20:27:51.686Z</atom:updated>
            <content:encoded><![CDATA[<pre>Please do not use DNS protocol for your application</pre><p>For more than 4 years I have been working exclusively with the DNS protocol and during this time I have collected a fairly large number of ways to shoot myself in the foot in a seemingly empty place.</p><p>DNS is great for the task of bringing visitors to your site or API endpoint, but that’s where use of DNS protocol in your application should end. If you need to publish some configuration for your clients or you’re looking for best protocol for service discovery then please do not use DNS.</p><p>Let’s follow the process of developing DNS client from scratch to highlight most obvious implementation issues you may experience. I must say right away that the number of good libraries for working with DNS is very small, I can only recommend <a href="https://github.com/miekg/dns">MiekG DNS</a>, although it is also not suitable as a client library. Almost all DNS client implementations present in the standard libraries of programming languages are oversimplified and have poor interfaces that hide many important details. I’m sure that my list of good libraries is incomplete, but that doesn’t mean they don’t exist.</p><p>We made sure that there is no implementation of the DNS protocol for our programming language, and we began to implement our own client. It is well known that DNS is one of the few protocols that uses the UDP protocol and we have already prepared a UDP client that establishes a connection to a remote host on which a recursive DNS resolver is expected to listen on port 53.</p><p>The next step is to try to tell the DNS server what we specifically want from it. Let’s look on DNS message diagram to get some idea about way to make query (thanks to <a href="https://www.inacon.de/">authors</a> of this image):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8UwoOXOeSPfr-gVLV3Okdw.jpeg" /></figure><p>It looks scary and very sophisticated for unprepared reader, but we see the Questions field and can guess that this is where we need to add our request (encoded in a special wire format of course).</p><p>The first problem you may encounter is that the word Question is plural. No, there is no possibility to request more than 1 record in real implementation of RFC compliant DNS servers, so you can ask just one question.</p><p>But what if your application supports dual stack (IPv4 + IPv6 addresses) and you don’t want to make two consecutive requests (A and then AAAA, although I would recommend the opposite sequence). Obviously, the ANY query type comes to the rescue, which will return all records.</p><p>This is another trap! Many DNS providers are moving away from the ANY type, and there is an <a href="https://tools.ietf.org/html/rfc8482">RFC</a> about it. For example, 1.1.1.1 does not support this type and you will receive NOTIMP in return. Therefore, you will have to do name resolution sequentially using two queries.</p><p>So, we got to the point where we created a DNS query that requests A record for <em>medium.com</em> domain. How will the server respond and will it respond? Actually it may not provide answer at all, but setting the exact limit, how long to wait for a response and how many times to repeat it is a very difficult task. In the wild environment of the Internet, this figure can vary from three hundreds of milliseconds to several thousand milliseconds. Therefore, be very careful with the limit.</p><p>The server responded! How do you know if the search for the requested name was successful? We look more closely and see the <em>rCode</em> field. What does a qualified programmer do? He/she goes to the <a href="https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6">IANA</a> site and looks at the allowed values for this field:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2bSQxqJI-a0WfCjI91KEqA.png" /></figure><p>A couple more seconds of careful search and common sense and we found <em>NoError.</em> Obviously, this is how the server reports that the name lookup was successful. Hooray!</p><p>Let’s look again at the picture with the structure of the DNS message and try to find exactly where to look for the answer. What is the difference between <em>answer</em>, <em>authority</em> and <em>additional</em>? Common sense can suggest that we may find answer in <em>answer</em> section but we still have no idea about purpose of other fields.</p><p>Will it always be this way? No. In the DNS protocol, it is perfectly normal (also known as NODATA) to return <em>rCode</em> set to <em>NoError</em> and an empty <em>Answer</em> section. In this case, the authority section will contain a completely unnecessary for us <em>SOA</em> record.</p><p>So, we come to the conclusion that the success of a DNS request can be determined by two checks: <em>rCode</em> == <em>NoError</em> and the <em>answer</em> section is not empty.</p><p>Hooray! We are close to a working DNS client. It’s time to try running it from a cloud server in order to test it in conditions closer to production. But here’s the bad luck. Our client just stopped working. We can see that <em>rCode</em> is equal to <em>NoError </em>and<em> </em>the <em>Answer</em> section is not empty, but there is no A record in it. Instead, it has some kind of <em>CNAME </em>string<em> </em>which points to another hostname and no traces of the IP addresses at all. This is where we come nearer to the reasons for my advice to avoid using DNS for applications unless other options exist.</p><p>Yes, <em>CNAME</em> responses are perfectly legitimate and are used by various recursive and authoritative server implementations. DNS servers can return a single <em>CNAME</em>, or they can return a chain of multiple <em>CNAMEs</em>, or even a <em>CNAME</em> and A/AAAA record. Each of these cases must be handled carefully and another (recursive only) request is required to get the IP address of the target server from CNAME.</p><p>For the next six months, our application works just fine and our client successfully receives a list of 3 backend servers from the DNS. Due to the increase in load, you decide to add 10 more servers. But something strange is happening. Only some of the servers are returned in the response from the DNS server.</p><p>What happened? So, we ran into the DNS response length limit — 512 bytes. What to do in this case? Time to uncover the skills of working with the TCP protocol and implement support for it in our DNS client. When server returns a response with the TC flag over the UDP protocol, the request must be repeated over TCP, which has no response size limitations.</p><p>Congratulations, we took into account almost all the well known issues and created a stable DNS client which works with all the variety of authoritative and recursive DNS servers.</p><p>Unfortunately, with the subsequent improvement of your client you will face more issues in quite unexpected places. For example, when trying to add a cache for your client, you will face the fact that the duration of caching for successful requests when the server responded with records and unsuccessful ones should be different and duration of caching must not exceeds values announced by remote server in TTL field for records or in SOA record for negative lookups.</p><p>Oh yes, one more issue. It is almost impossible to distinguish a temporary DNS server failure from a permanent one, since in both cases you will see <em>SERVFAIL.</em></p><p>I hope you will not use DNS protocol where it is not needed and will serve configuration to your applications in <em>JSON</em> format using <em>HTTPS</em> protocol.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f7229564a3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>