<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://naccy.de/feed.xml" rel="self" type="application/atom+xml" /><link href="https://naccy.de/" rel="alternate" type="text/html" /><updated>2024-10-01T16:51:45+00:00</updated><id>https://naccy.de/feed.xml</id><title type="html">Quentin’s log</title><entry><title type="html">An update on bpfilter</title><link href="https://naccy.de/2024/10/01/bpfilter-status-report.html" rel="alternate" type="text/html" title="An update on bpfilter" /><published>2024-10-01T00:00:00+00:00</published><updated>2024-10-01T00:00:00+00:00</updated><id>https://naccy.de/2024/10/01/bpfilter-status-report</id><content type="html" xml:base="https://naccy.de/2024/10/01/bpfilter-status-report.html"><![CDATA[<p>This post will detail the current state of <code class="language-plaintext highlighter-rouge">bpfilter</code> and how it approaches features and constraints for packet filtering.</p>

<p>The project has witnessed significant progress over the last couple of months, comparable to the progress made during the whole prior year: there has been a significant increase in development pace. It’s a well-known fact that the number of commits in a project isn’t reflective of the quality of the work, but lacking a better indicator: the project recorded <a href="https://github.com/facebook/bpfilter/commits/main/?since=2023-07-01&amp;until=2024-07-31">257 contributions between July 2023 and August 2024</a>, but <a href="https://github.com/facebook/bpfilter/commits/main/?since=2024-08-01&amp;until=2024-09-30">229 contributions over the last two months</a>.</p>

<h2 id="current-state">Current State</h2>

<p><strong>Documentation</strong></p>

<p>The <code class="language-plaintext highlighter-rouge">bpfilter</code> documentation is automatically generated and published at <a href="https://bpfilter.io/">bpfilter.io</a> for every merged pull request. The documentation is split in two parts: the user documentation, which explains how to use <code class="language-plaintext highlighter-rouge">bpfilter</code>, and the developer documentation, which details the project’s internals.</p>

<p>The user documentation has been updated with existing features. The <a href="https://bpfilter.io/usage/index.html">“Usage”</a> page is a good starting point if you want to try <code class="language-plaintext highlighter-rouge">bpfilter</code>. The developer documentation has also been improved, but to a lesser extent: it’s accurate, but not all the components are documented.</p>

<p>There was previously a page on <a href="https://bpfilter.io/">bpfilter.io</a> that would contain a reference to the complete internal API of the project. This page was filled with unorganized internal API details, brought no value to the documentation, and was very slow to generate. It has been removed in favor of a per-component documentation, which is more usable.</p>

<p>Apart from improving the documentation by importing more of the source code documentation into it, the developer documentation would also benefit from a high-level overview of the project: what are the different components and how they work together. A few schema and diagrams would help!</p>

<p>Finally, <code class="language-plaintext highlighter-rouge">bpfilter</code> crossed 100 stars on GitHub (125 and counting!), and a logo was designed to celebrate this milestone!</p>

<figure style="text-align: center;">
  <img style="display: block; margin: auto;" src="/assets/2024-10-01-bpfilter-logo.png" alt="bpfilter logo" width="350" />
  <figcaption style="padding-top: 15px;"><code>bpfilter</code> logo</figcaption>
</figure>

<p><strong>Front-ends</strong></p>

<blockquote>
  <p>Front-ends are the components used to translate the filtering rules coming from <code class="language-plaintext highlighter-rouge">nftables</code>/<code class="language-plaintext highlighter-rouge">iptables</code>/<code class="language-plaintext highlighter-rouge">bfcli</code> into an internal format which used to generate the BPF programs.</p>
</blockquote>

<p>Let’s start with <code class="language-plaintext highlighter-rouge">iptables</code>: not much has changed. You can still filter on IP address (source and destination), protocol, and network interface. Not all the new matchers have yet been integrated into the <code class="language-plaintext highlighter-rouge">iptables</code> front-end, but will soon.</p>

<p><code class="language-plaintext highlighter-rouge">nftables</code>, on the other hand, is not in a good shape. Recent progress on <code class="language-plaintext highlighter-rouge">bpfilter</code> revealed some limitations to this front-end and the need to refactor it in a way that would allow it to evolve. Unfortunately, I don’t have the bandwidth to do it right now, but it’s one of my top priorities. To provide more context, <code class="language-plaintext highlighter-rouge">nft</code> (<code class="language-plaintext highlighter-rouge">nftables</code>’ command line interface) will parse the filtering rules, convert them into <code class="language-plaintext highlighter-rouge">nftables</code> bytecode, and send them to the kernel. <code class="language-plaintext highlighter-rouge">bpfilter</code> has to work from this bytecode and convert it into an internal ruleset representation, which is not an easy task. The trick is to successfully map one or more instructions back to a single object in <code class="language-plaintext highlighter-rouge">bpfilter</code> (usually a matcher). I look forward to when I’ll have enough time to actually fix this once and for all.</p>

<p>A third front-end (and CLI) has been added to <code class="language-plaintext highlighter-rouge">bpfilter</code> during the last months: <code class="language-plaintext highlighter-rouge">bfcli</code>. <code class="language-plaintext highlighter-rouge">bfcli</code> provides more flexibility to combine different features provided by <code class="language-plaintext highlighter-rouge">bpfilter</code>: filter on XDP or a cgroup, drop a specific IPv4 address, match a layer 4 protocol or IPv6 optional field. Not all those combinations can be done using <code class="language-plaintext highlighter-rouge">iptables</code> or <code class="language-plaintext highlighter-rouge">nftables</code>. Because <code class="language-plaintext highlighter-rouge">bfcli</code> uses <code class="language-plaintext highlighter-rouge">bpfilter</code>’s internal structures to represent the filtering rules, integrating and testing new features is easier and faster: no translation layer needed. The ruleset is serialized by <code class="language-plaintext highlighter-rouge">bfcli</code>, sent to the daemon, and deserialized. <code class="language-plaintext highlighter-rouge">bfcli</code> is not meant to be the main CLI for <code class="language-plaintext highlighter-rouge">bpfilter</code>, nor a replacement for <code class="language-plaintext highlighter-rouge">nftables</code> or <code class="language-plaintext highlighter-rouge">iptables</code>, but a different tool for different use cases. If you are eager to know more about <code class="language-plaintext highlighter-rouge">bfcli</code>, read the <a href="https://bpfilter.io/usage/bfcli.html">documentation</a>. Here’s a commented example of a ruleset:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp"># Create a chain attached to XDP, accept packets that doesn't match any rule.
</span><span class="n">chain</span> <span class="n">BF_HOOK_XDP</span> <span class="n">policy</span> <span class="n">ACCEPT</span>
    <span class="n">rule</span>
        <span class="cp"># Drop packets coming from 192.168.1.{131,132}
</span>        <span class="cp"># Keep a counter of the number of packets and bytes dropped
</span>        <span class="n">ip4</span><span class="p">.</span><span class="n">saddr</span> <span class="n">in</span> <span class="p">{</span><span class="mi">192</span><span class="p">.</span><span class="mi">168</span><span class="p">.</span><span class="mi">1</span><span class="p">.</span><span class="mi">131</span><span class="p">,</span><span class="mi">192</span><span class="p">.</span><span class="mi">168</span><span class="p">.</span><span class="mi">1</span><span class="p">.</span><span class="mi">132</span><span class="p">}</span>
        <span class="n">counter</span>
        <span class="n">DROP</span>
    <span class="n">rule</span>
        <span class="cp"># Drop packets coming from fc00::fbaf:7b6b:ba41:abce
</span>        <span class="n">ip6</span><span class="p">.</span><span class="n">saddr</span> <span class="n">fc00</span><span class="o">::</span><span class="n">fbaf</span><span class="o">:</span><span class="mi">7</span><span class="n">b6b</span><span class="o">:</span><span class="n">ba41</span><span class="o">:</span><span class="n">abce</span>
        <span class="n">DROP</span>
</code></pre></div></div>

<p><strong>Filtering rules</strong></p>

<p>The way <code class="language-plaintext highlighter-rouge">bpfilter</code> defines filtering rules has also evolved since 2023: the structure is now simpler, easier to understand.</p>

<p>The <code class="language-plaintext highlighter-rouge">chain</code> is the high-level object used by <code class="language-plaintext highlighter-rouge">bpfilter</code> to represent filtering rules. A chain will be converted into a BPF program, then attached to a specific hook in the kernel. Consequently, a chain is composed of:</p>

<ul>
  <li>The name of the hook it should filter from</li>
  <li>A default action (<code class="language-plaintext highlighter-rouge">policy</code>) to perform in case no rule matches the packet</li>
  <li>A list of sets, which are described below</li>
  <li>A list of rules</li>
</ul>

<figure style="text-align: center;">
  <img style="display: block; margin: auto;" src="/assets/2024-10-01-bf_chain.png" alt="bf_chain structure" width="250" />
  <figcaption>A chain for <code>bpfilter</code></figcaption>
</figure>

<p>The <code class="language-plaintext highlighter-rouge">set</code> is a new type of object introduced recently, and it behaves similarly to the sets defined in <code class="language-plaintext highlighter-rouge">nftables</code>: you can create a set containing multiple elements of the same type, and filter on this set using a single instruction. Sets are centralized within the chain, so they could be used by multiple rules.</p>

<p>A <code class="language-plaintext highlighter-rouge">rule</code> now contains one or more <code class="language-plaintext highlighter-rouge">matchers</code>. A matcher represents a matching criterion for a packet: it could match against the packet’s IPv6 source address, or a TCP flag, or the layer 3 protocol type. The <a href="https://bpfilter.io/usage/bfcli.html#matchers">documentation</a> contains the list of matchers supported by <code class="language-plaintext highlighter-rouge">bfcli</code> and the <a href="https://github.com/facebook/bpfilter/blob/0a1df7c79a3fc1a1d84efd63472a41359f80d8f3/src/core/matcher.h#L138-L148">definition of a matcher</a>. Apart from a list of <code class="language-plaintext highlighter-rouge">matchers</code>, a rule also contains a <code class="language-plaintext highlighter-rouge">verdict</code> to apply to the packet if the <code class="language-plaintext highlighter-rouge">matchers</code> match, and a boolean to state whether <code class="language-plaintext highlighter-rouge">bpfilter</code> should maintain a counter of bytes and packets matched by the rule.</p>

<figure style="text-align: center;">
  <img style="display: block; margin: auto;" src="/assets/2024-10-01-bf_rule.png" alt="bf_rule structure" width="250" />
  <figcaption>A rule for <code>bpfilter</code></figcaption>
</figure>

<p><strong>Bytecode generation</strong></p>

<p>The logic used by <code class="language-plaintext highlighter-rouge">bpfilter</code> to generate the bytecode evolves and grows according to the new features introduced in the codebase. Matchers are a good example of this, as they require specific bytecode to be generated to properly parse the packet and compare it to reference data.</p>

<p><code class="language-plaintext highlighter-rouge">bpfilter</code> relies on a codegen (<code class="language-plaintext highlighter-rouge">struct bf_cgen</code>) object to represent the bytecode generation context. A codegen contains a reference to a chain (the ruleset), and a BPF program (<code class="language-plaintext highlighter-rouge">struct bf_program</code>).</p>

<p>Originally, <code class="language-plaintext highlighter-rouge">bpfilter</code> would create multiple programs for a codegen: one program for each network interface. But this was a subpar solution: some hooks are defined per-interface (e.g. XDP), while others apply to every network interface (<code class="language-plaintext highlighter-rouge">BPF_NETFILTER</code>). This behavior has been modified so a codegen generates a single BPF program, but multiple codegens can be defined for XDP and TC hooks. A user can choose which interface to attach their XDP or TC chain using the <a href="https://bpfilter.io/usage/bfcli.html#chains">hook’s <code class="language-plaintext highlighter-rouge">ifindex</code> option</a>.</p>

<p>Each BPF program generated for a codegen will be called every time a packet passes through the hook it is attached to and perform the following action:</p>
<ul>
  <li>Initialize a small runtime context to store metadata that might be used to filter the packet more efficiently</li>
  <li>Execute the filtering rules in the order they are defined in the chain, such that:
    <ul>
      <li>If every <code class="language-plaintext highlighter-rouge">matcher</code> of the rule matches the packet, it means the rule itself matched the packet, and we can update the counter (if the rule has counters), stop processing subsequent rules, and return the rule’s verdict</li>
      <li>If at least one of the <code class="language-plaintext highlighter-rouge">matcher</code>s doesn’t match the packet, we stop processing the current rule and continue with the next one</li>
    </ul>
  </li>
  <li>Once we processed all the rules, if we haven’t returned yet, it means no rule matched the packet, and we can then return the chain’s policy (default action)</li>
</ul>

<figure style="text-align: center;">
  <img style="display: block; margin: auto;" src="/assets/2024-10-01-codegen.png" alt="BPF program structure" width="350" />
  <figcaption>Structure of a BPF program generated by <code>bpfilter</code></figcaption>
</figure>

<p>The main change to the bytecode generation impacts how a packet is pre-processed by the BPF program. The BPF program will parse the headers (L2, L3, L4) of the packet, store relevant metadata (protocol, header size) into the program’s runtime context. Pre-processing the packet’s headers reduces a matcher to two actions: check if the packet contains the protocol the matcher supports (e.g. only IPv6 packets can be processed by an IPv6 source address matcher), and perform the actual comparison with the matcher’s reference data. This behavior allows a chain to define rules to filter different protocols from the same layer (e.g. filtering on IPv4 and IPv6 in the same chain).</p>

<p>The size of the generated bytecode has been decreased by removing superfluous instructions and simplifying some features.</p>

<p><strong>Tests and quality</strong></p>

<p><code class="language-plaintext highlighter-rouge">bpfilter</code> relies heavily on unit tests, the code coverage has increased since the last update and pull requests are not allowed to reduce the overall coverage.</p>

<p>Currently, there is a big blind spot to <code class="language-plaintext highlighter-rouge">bpfilter</code> testing, which is the bytecode generation component. The generated bytecode is not automatically tested, nor is it automatically testable at the moment. This is an issue that will grow as <code class="language-plaintext highlighter-rouge">bpfilter</code> supports more and more features. A solution to this issue is described in the <a href="#next">Next</a> section below.</p>

<p><strong>Project management</strong></p>

<p>Waiting to publish an update after a year is clearly too long. The intention going forward is for more regular updates, which will benefit both users and maintainers.</p>

<p>Until I can establish a more centralized location for the roadmap and milestones, I will add tasks to the GitHub Project and create the relevant GitHub issues for those. You can take a look at the <a href="https://github.com/facebook/bpfilter/issues">open issues</a> if you want to have an idea of the current work.</p>

<h2 id="next">Next</h2>

<p>Now let’s take some time to focus on the future of the project. Most of the latest <code class="language-plaintext highlighter-rouge">bpfilter</code> features are derived from an internal need at Meta, but I would like to work more on external integrations.</p>

<p><strong>Extent filtering capabilities (H2 2024)</strong></p>

<ul>
  <li>Support for cgroup hooks, to attach a generated BPF program directly to a cgroup</li>
  <li>Improve <code class="language-plaintext highlighter-rouge">sets</code> support: sets are quite new to <code class="language-plaintext highlighter-rouge">bpfilter</code> and they will be expanded to support more types of data (IPv6, combination of IP and port, etc.)</li>
  <li>Expand existing matchers with more operators</li>
  <li>Support ranges (e.g. port range)</li>
</ul>

<p><strong>Packaging <code class="language-plaintext highlighter-rouge">bpfilter</code> for RPM/DEB (H2 2024)</strong></p>

<p>Currently, you need to manually build <code class="language-plaintext highlighter-rouge">bpfilter</code> if you want to test it. It’s cumbersome and could repel potential users. Packaging <code class="language-plaintext highlighter-rouge">bpfilter</code> into a DEB and RPM package will remove this limitation and could grow the number of users and contributors.</p>

<p><strong>Fix <code class="language-plaintext highlighter-rouge">nftables</code> support (H2 2024?)</strong></p>

<p>Support for <code class="language-plaintext highlighter-rouge">nftables</code> is essential. <code class="language-plaintext highlighter-rouge">nftables</code> requires a custom patch to support <code class="language-plaintext highlighter-rouge">bpfilter</code>, this patch is in the project’s repository, and <code class="language-plaintext highlighter-rouge">nftables</code> can be built easily with <code class="language-plaintext highlighter-rouge">make nftables</code>. I would love to see <code class="language-plaintext highlighter-rouge">nftables</code> use <code class="language-plaintext highlighter-rouge">bpfilter</code> as a way to offload filtering to XDP in the future. I would like to spend time on this task: I think it could benefit both <code class="language-plaintext highlighter-rouge">bpfilter</code> and <code class="language-plaintext highlighter-rouge">nftables</code>.</p>

<p><strong>End-to-end testing (H1 2025)</strong></p>

<p>End-to-end testing is currently non-existent, but it’s a critical part to ensure <code class="language-plaintext highlighter-rouge">bpfilter</code> is reliable. Given 3 front-ends and many matchers, end-to-end testing is the only way to quickly validate the generated programs. A solution  would be to create a testing framework to perform the following:</p>

<ul>
  <li>Manage <code class="language-plaintext highlighter-rouge">bpfilter</code> lifetime: start/stop the daemon, clean-up the cache or the BPF programs if needed</li>
  <li>Define filtering rules using <code class="language-plaintext highlighter-rouge">bfcli</code>.</li>
  <li>Craft packets and compare the program’s behavior to the expected results. The framework could send the packet to the interface the chain is attached to and read the rules counters to ensure the packet was accepted/dropped as expected.</li>
</ul>

<p><strong>Smarter bytecode generation</strong></p>

<p>Reducing the bytecode size would improve performance of the generated BPF program. This could be done by parsing protocol headers based on usage. A chain that doesn’t contain a matcher for the TCP protocol doesn’t need to parse the TCP header, or include any logic that refers to the TCP protocol. Similarly, a chain matching exclusively on layer 3 protocols doesn’t need any logic to parse the layer 4 protocols.</p>

<p>Additionally, the preprocessing logic could be generated once (and cached) as it’s identical from a program to another, or even better: be implemented in C as part of <code class="language-plaintext highlighter-rouge">bpfilter</code>’s sources and copied directly to the final BPF programs.</p>

<p><strong>Custom bytecode</strong></p>

<p>What if a user could write C code to perform whatever complex packet filtering logic they want to, compile it and send it to <code class="language-plaintext highlighter-rouge">bpfilter</code> to be used in a chain? <code class="language-plaintext highlighter-rouge">bpfilter</code> could generate the BPF program as it does currently, but one of the rules (or matcher) would defer its verdict to a user-provided BPF function. This would allow users to define their own filtering logic, without relying on <code class="language-plaintext highlighter-rouge">bpfilter</code>’s developers to implement the required matchers.</p>

<p>This idea was originally suggested by Daniel Borkmann and it seems promising.</p>

<h2 id="final-word">Final word</h2>

<p>This post is long enough already, so I’ll cut it short: if you have any questions, if you need help with <code class="language-plaintext highlighter-rouge">bpfilter</code>, if you have any feedback, please reach out to <code class="language-plaintext highlighter-rouge">qde@naccy.de</code>! :)</p>]]></content><author><name></name></author><summary type="html"><![CDATA[This post will detail the current state of bpfilter and how it approaches features and constraints for packet filtering.]]></summary></entry><entry><title type="html">bpfilter 2023 H1 status report</title><link href="https://naccy.de/2023/07/11/bpfilter-status-report.html" rel="alternate" type="text/html" title="bpfilter 2023 H1 status report" /><published>2023-07-11T00:00:00+00:00</published><updated>2023-07-11T00:00:00+00:00</updated><id>https://naccy.de/2023/07/11/bpfilter-status-report</id><content type="html" xml:base="https://naccy.de/2023/07/11/bpfilter-status-report.html"><![CDATA[<p>There have been a lot of changes on <code class="language-plaintext highlighter-rouge">bpfilter</code> in the past half, I’ll try to summarise all of it within this report! For a 30min summary, you can check <code class="language-plaintext highlighter-rouge">bpfilter</code>’s presentation <a href="https://www.youtube.com/watch?v=UDZhCubE-Kk">at LSFMM+BPF this year</a>!</p>

<h1 id="lets-summarise">Let’s summarise</h1>

<p>6 months ago, <code class="language-plaintext highlighter-rouge">bpfilter</code> was a kernel usermode helper. Meaning a kernel module that would start a userspace program once loaded. It would then hook to <code class="language-plaintext highlighter-rouge">getsockopt()</code> and <code class="language-plaintext highlighter-rouge">setsockopt()</code> to catch <code class="language-plaintext highlighter-rouge">iptables</code>’ calls and bypass the <code class="language-plaintext highlighter-rouge">iptables</code>’ backend.</p>

<p>While this design had a lot of advantages over a standard kernel module, it wasn’t exempt from disadvantages compared to a full userspace program:</p>
<ul>
  <li>Getting reviews and feedback from kernel maitainers can be long, leading to slower iterations.</li>
  <li>Lack of flexibility in development and limited use cases as <code class="language-plaintext highlighter-rouge">bpfilter</code> was highly tied to <code class="language-plaintext highlighter-rouge">iptables</code> and its usage.</li>
  <li>Some features could not be developed because of the usermode helper constraints.</li>
</ul>

<p>Eventually, the decision was taken to change <code class="language-plaintext highlighter-rouge">bpfilter</code> into a userspace program (fully userspace, not a usermode helper anymore). <code class="language-plaintext highlighter-rouge">bpfilter</code> could then be removed from the kernel tree, to live in a dedicated GitHub repository. As you can see in the first commits <a href="https://github.com/facebook/bpfilter/blob/7f8308a4c52a869b2728e8f6b531aa2695b721fd/README.md">in the official GitHub repository</a>, <code class="language-plaintext highlighter-rouge">bpfilter</code> was for a time available as an out-of-tree kernel module, before becoming a userspace program.</p>

<p><strong>What about the usermode helper in the kernel tree?</strong> It still lives there, as it’s not harming anyone. Eventually, I’ll send a patch to remove this code, as it’s not needed anymore.</p>

<p>Long story short: 6 months ago, <code class="language-plaintext highlighter-rouge">bpfilter</code> was a backend for <code class="language-plaintext highlighter-rouge">iptables</code>. Now, <code class="language-plaintext highlighter-rouge">iptables</code> is a front-end for <code class="language-plaintext highlighter-rouge">bpfilter</code>.</p>

<h1 id="moving-bpfilter-to-userspace">Moving <code class="language-plaintext highlighter-rouge">bpfilter</code> to userspace</h1>

<p>I was intentionally vague in describing <code class="language-plaintext highlighter-rouge">bpfilter</code> as a “userspace program” to leave all the details in this section, so let’s see exactly what this means!</p>

<p>Moving <code class="language-plaintext highlighter-rouge">bpfilter</code> to userspace is a big piece of work; let’s define what this involves, just to be clear:</p>
<ul>
  <li>All the kernel-specific code has to be removed. This can be very tedious, depending on the amount of internal APIs used. For example, many BPF instructions (e.g. <code class="language-plaintext highlighter-rouge">BPF_ALU64_IMM</code>) are only defined in the kernel’s internal API. Another noticeable miss is the kernel’s linked list, which I had to rewrite (and drop unnecessary constraints on the way).</li>
  <li>Move away from the <code class="language-plaintext highlighter-rouge">iptables</code>-specific design and implementation: <code class="language-plaintext highlighter-rouge">bpfilter</code> only supports <code class="language-plaintext highlighter-rouge">iptables</code>, so it is internally very close to <code class="language-plaintext highlighter-rouge">iptables</code>’ internal structure and APIs. Having <code class="language-plaintext highlighter-rouge">bpfilter</code> as a userspace program would allow more clients than just <code class="language-plaintext highlighter-rouge">iptables</code> but requires decoupling <code class="language-plaintext highlighter-rouge">iptables</code>-specific code.</li>
  <li>Ensure <code class="language-plaintext highlighter-rouge">iptables</code> still work. The <code class="language-plaintext highlighter-rouge">bpfilter</code> kernel module could hook to the <code class="language-plaintext highlighter-rouge">iptables</code>’ <code class="language-plaintext highlighter-rouge">getsockopt()</code> and <code class="language-plaintext highlighter-rouge">setsockopt()</code> calls, and bypass the kernel to answer the calls directly. This is impossible from userspace, so I had to find a way to preserve this feature.</li>
</ul>

<p>The choice settled on having <code class="language-plaintext highlighter-rouge">bpfilter</code> split into two parts:</p>
<ul>
  <li>The <strong>daemon</strong> listens on a Unix Domain Socket (UDS). It processes incoming requests according to the content and sends the response back. It can generate a BPF program from scratch and attach it to the kernel.</li>
  <li>The <strong>library</strong> communicates with the daemon through the UDS. It’s lightweight and aims to be linked to the client. The library performs no complex operation: the daemon handles the heavy work.</li>
</ul>

<h2 id="design">Design</h2>
<p>Let’s have a look at the main structures used in <code class="language-plaintext highlighter-rouge">bpfilter</code>:</p>

<p><img src="/assets/2023-07-11-bpfilter-structure.png" alt="bpfilter structure" /></p>

<ul>
  <li><strong>Context</strong> (<code class="language-plaintext highlighter-rouge">bf_context</code>) is the global context of the daemon, used to store the current state of the application. The context can be serialised to disk and restored, which is necessary if we want to restart the <code class="language-plaintext highlighter-rouge">bpfilter</code> daemon without losing the state of loaded BPF programs and maps. Serialised data is also used to store client-specific data: for example, with <code class="language-plaintext highlighter-rouge">iptables</code>, it stores the set of rules in <code class="language-plaintext highlighter-rouge">iptables</code> format, so we don’t have to translate the BPF programs back into <code class="language-plaintext highlighter-rouge">iptables</code> internal structures for each request.</li>
  <li><strong>Codegen</strong> (<code class="language-plaintext highlighter-rouge">bf_codegen</code>) is the structure used to represent filtering rules for a <code class="language-plaintext highlighter-rouge">(front, hook)</code> tuple. For example, all the <code class="language-plaintext highlighter-rouge">iptables</code> rules attached to the <code class="language-plaintext highlighter-rouge">iptables</code>’ <code class="language-plaintext highlighter-rouge">INPUT</code> hook will be stored within the same codegen. This way, rules are grouped together and generated into the same BPF program for a common <code class="language-plaintext highlighter-rouge">(front, hook)</code>, while fronts remain independent from each other.</li>
  <li><strong>Programs</strong> (<code class="language-plaintext highlighter-rouge">bf_program</code>) are… the BPF programs. Currently, there is 1 BPF program generated for each interface, for each <code class="language-plaintext highlighter-rouge">(front, hook)</code> set, allowing for interface-specific filtering rules. Each program has its own BPF map to store the rules’ counters: the number of packets and bytes processed by each rule.</li>
</ul>

<p>To summarise, the global context will store a codegen for each <code class="language-plaintext highlighter-rouge">(front, hook)</code> tuple, generating a BPF program for each interface.</p>

<h2 id="more-about-the-daemon">More about the daemon</h2>
<p>The daemon will listen for incoming requests on a UDS. Each request will contain details about the source (e.g. <code class="language-plaintext highlighter-rouge">iptables</code>), the actual request (e.g. replace filtering rules, or fetch counters), and the client-specific data that form the request (e.g. list of rules or counters to fetch).</p>

<p><img src="/assets/2023-07-11-bpfilter-libbpfilter.png" alt="bpfilter and libbpfilter" /></p>

<p>When the request is received, it’s time for <strong>translation</strong>: the daemon will translate the client-specific data into a generic format specific to <code class="language-plaintext highlighter-rouge">bpfilter</code>; bytecode generation can be shared between multiple fronts. Because of this structure, adding support for a new front (say Tupperware Firewall) comes down to adding the code to translate this front’s data format. The generic data is sent to the generation function after the translation.</p>

<blockquote>
  <p>Before we continue, let’s talk about “flavor” (or “flavour”), as it’s a term used in the codebase. Do you see how the prototype of a BPF program’s main function differs between TC and XDP? And so is the return value’s meaning? And so are multiple other things, which depend on the BPF program type? Well, from <code class="language-plaintext highlighter-rouge">bpfilter</code>’s point of view, that’s a “flavor”. It’s used to generate boilerplate BPF bytecode specific to the BPF program type, so all the programs (whatever their “flavor” is) could be generated the same way.</p>
</blockquote>

<p>The BPF program <strong>generation</strong> feeds from the generic <code class="language-plaintext highlighter-rouge">bpfilter</code> data structures: codegens from the request are provided by the translation function, and the generation function will then create the BPF programs for it. Using the flavor-specific callbacks (<code class="language-plaintext highlighter-rouge">struct bf_flavor_ops</code>), it will generate a boilerplate to store the packet size, initialise a couple of registers, and then unroll all the filtering rules into BPF bytecode to be evaluated sequentially at runtime. When all the rules and the code for counters update are generated, the programs are pushed to the management function of <code class="language-plaintext highlighter-rouge">bpfilter</code>.</p>

<p>The last part of the process is <strong>management</strong> (for lack of a better name). This part will use the flavor-specific functions to load the BPF programs to the kernel and attach them to their hook. Any existing <code class="language-plaintext highlighter-rouge">bpfilter</code> program previously loaded and attached for this <code class="language-plaintext highlighter-rouge">(front, hook, interface)</code> set will be unloaded.</p>

<h2 id="and-what-about-the-library">And what about the library?</h2>
<p>Well, as I described earlier, it’s lightweight, so let’s keep it short. <code class="language-plaintext highlighter-rouge">libbpfilter</code> currently offers an <code class="language-plaintext highlighter-rouge">iptables</code>-specific interface. Eventually, a generic front-end will be available. The idea behind <code class="language-plaintext highlighter-rouge">libbpfilter</code> is to simplify its usage as much as possible by providing API using client-specific data.</p>

<p><strong>What does it look like for <code class="language-plaintext highlighter-rouge">iptables</code>?</strong> You’re probably wondering. Let’s have a look:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#if defined(ENABLE_BPFILTER) &amp;&amp; !defined(_LIBIP6TC_H)
</span>    <span class="k">if</span> <span class="p">(</span><span class="n">handle</span><span class="o">-&gt;</span><span class="n">use_bpf</span><span class="p">)</span>
        <span class="n">ret</span> <span class="o">=</span> <span class="n">bf_ipt_replace</span><span class="p">(</span><span class="n">repl</span><span class="p">);</span>
    <span class="k">else</span>
<span class="cp">#endif
</span>    <span class="n">ret</span> <span class="o">=</span> <span class="n">setsockopt</span><span class="p">(</span><span class="n">handle</span><span class="o">-&gt;</span><span class="n">sockfd</span><span class="p">,</span> <span class="n">TC_IPPROTO</span><span class="p">,</span> <span class="n">SO_SET_REPLACE</span><span class="p">,</span> <span class="n">repl</span><span class="p">,</span>
                     <span class="k">sizeof</span><span class="p">(</span><span class="o">*</span><span class="n">repl</span><span class="p">)</span> <span class="o">+</span> <span class="n">repl</span><span class="o">-&gt;</span><span class="n">size</span><span class="p">);</span>
	<span class="k">if</span> <span class="p">(</span><span class="n">ret</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
		<span class="k">goto</span> <span class="n">out_free_newcounters</span><span class="p">;</span>
</code></pre></div></div>

<p>What you can see above is part of an <code class="language-plaintext highlighter-rouge">iptables</code> proof of concept to demonstrate how would <code class="language-plaintext highlighter-rouge">bpfilter</code> be integrated (more on that later). Let’s skip the <code class="language-plaintext highlighter-rouge">#if</code> and <code class="language-plaintext highlighter-rouge">#endif</code> shenanigans: we see a three-line change to support <code class="language-plaintext highlighter-rouge">bpfilter</code> in <code class="language-plaintext highlighter-rouge">iptables</code>. Either <code class="language-plaintext highlighter-rouge">handle-&gt;use_bpf</code> is true, in which case we call <code class="language-plaintext highlighter-rouge">bf_ipt_replace()</code> from <code class="language-plaintext highlighter-rouge">libbpfilter</code>, or it’s false, and we use the old <code class="language-plaintext highlighter-rouge">setsockopt()</code> behaviour. As you can see, <code class="language-plaintext highlighter-rouge">bf_ipt_replace()</code> uses <code class="language-plaintext highlighter-rouge">ipables</code>’s data structures (<code class="language-plaintext highlighter-rouge">repl</code>) without modification, leading to a simple integration.</p>

<h1 id="fresh-new-features">Fresh new features</h1>

<p>That was a lot of things, but wait, there’s more! The previous section described the work I had to do to have <code class="language-plaintext highlighter-rouge">bpfilter</code> running as a userspace program so that we could expect the same features as <code class="language-plaintext highlighter-rouge">bpfilter.ko</code>. But I’ve added more features on the way; some are implied in the previous sections, but some are not discussed. Here is a list of some of the features added in the past months:</p>

<ul>
  <li><strong>Support for functions</strong>: previously, all the code in the generated BPF program was inlined. It worked great, but some features (such as updating the counters map) were generated multiple times in every BPF program (1 for each rule). Now, during program generation, a fixup for a function call can be added to be processed later. Then, <code class="language-plaintext highlighter-rouge">bpfilter</code> will check the function call fixups declared for a given <code class="language-plaintext highlighter-rouge">bf_program</code>, add the relevant functions after the program’s <code class="language-plaintext highlighter-rouge">exit</code> instruction, and update the jump offset of the fixup!</li>
  <li><strong>Support for multiple interfaces</strong> was discussed in the previous section. While the codegen structure is inherited from <code class="language-plaintext highlighter-rouge">bpfilter.ko</code>, the was no support for more than one static interface. Hence, <code class="language-plaintext highlighter-rouge">bf_program</code> has been introduced. A <code class="language-plaintext highlighter-rouge">bf_codegen</code> will contain a program for each interface (except for the loopback interface) and generate each <code class="language-plaintext highlighter-rouge">bf_program</code> according to the rules to attach to each interface. As a result, we can now do <code class="language-plaintext highlighter-rouge">iptables -I INPUT -i enp0s5 -j DROP -p icmp</code>!</li>
  <li><strong>(Un)serialise <code class="language-plaintext highlighter-rouge">bpfilter</code>’s context</strong> was also discussed in the previous section. It comes from a comment from my LSFMM/BPF talk in May: what happens if we restart <code class="language-plaintext highlighter-rouge">bpfilter</code>? At the time, <code class="language-plaintext highlighter-rouge">bpfilter</code> would forget all the loaded programs and maps! It’s not the case anymore: <code class="language-plaintext highlighter-rouge">bpfilter</code> will serialise its internal state to <code class="language-plaintext highlighter-rouge">/run/bpfilter.blob</code> after each write operation (i.e. operation modifying the filtering rules), then restore its internal context from it on start (or restart).</li>
  <li><strong>Overall code quality checks</strong>: I like my code style to be consistent, but it’s 2023 I shouldn’t spend time enforcing it, so <code class="language-plaintext highlighter-rouge">clang-format</code> will do it for me, thanks to <code class="language-plaintext highlighter-rouge">.clang-format</code> in <code class="language-plaintext highlighter-rouge">bpfilter</code>’s source code root folder. A <code class="language-plaintext highlighter-rouge">.clang-tidy</code> file is also present, even though checks are subject to change. A coverage target is available (<code class="language-plaintext highlighter-rouge">make coverage</code>) to write a nice HTML coverage summary (see <code class="language-plaintext highlighter-rouge">$BUILD/doc/coverage/index.html</code>). Finally, <code class="language-plaintext highlighter-rouge">make doc</code> will generate the documentation with Doxygen and Sphinx (see <code class="language-plaintext highlighter-rouge">$BUILD/doc/html/index.html</code>). Documentation would need some love, but it’s only the beginning, and I expect it to be more complete and precise over time.</li>
  <li>A lot of minor improvements here and there!</li>
</ul>

<p>Last but not least, and also not a new feature, I’ve been working on an <code class="language-plaintext highlighter-rouge">iptables</code> integration proof-of-concept! You can get it <a href="https://github.com/qdeslandes/iptables/tree/bpfilter">on GitHub</a>. It’s straightforward to integrate to <code class="language-plaintext highlighter-rouge">libbpfilter</code> (see the last two commits), this fork will behave exactly as <code class="language-plaintext highlighter-rouge">iptables</code> would, but if you pass the <code class="language-plaintext highlighter-rouge">--bpf</code> flag, then it uses <code class="language-plaintext highlighter-rouge">bpfilter</code> under the hood!</p>

<h1 id="whats-next">What’s next?</h1>

<p>2023 H2 will be focused on improving <code class="language-plaintext highlighter-rouge">bpfilter</code> support for <code class="language-plaintext highlighter-rouge">iptables</code>, creating a proof-of-concept for <code class="language-plaintext highlighter-rouge">nftables</code>, and supporting more and more features: IPv6, connection tracking…</p>]]></content><author><name></name></author><summary type="html"><![CDATA[There have been a lot of changes on bpfilter in the past half, I’ll try to summarise all of it within this report! For a 30min summary, you can check bpfilter’s presentation at LSFMM+BPF this year!]]></summary></entry></feed>