<?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://balagetech.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://balagetech.com/" rel="alternate" type="text/html" /><updated>2026-11-27T13:33:10+00:00</updated><id>https://balagetech.com/feed.xml</id><title type="html">Balagetech</title><subtitle>Engineer this, engineer that, engineer everything.. then ruin all the fun with a single typo.</subtitle><author><name>Balázs Németh</name></author><entry><title type="html">Introducing ‘whatsthedamage’ to process your bank exports</title><link href="https://balagetech.com/2025/01/07/introducing-whatsthedamage-to-process-your-bank-account-exports/" rel="alternate" type="text/html" title="Introducing ‘whatsthedamage’ to process your bank exports" /><published>2025-01-07T13:16:07+00:00</published><updated>2025-01-07T13:16:07+00:00</updated><id>https://balagetech.com/2025/01/07/introducing-whatsthedamage-to-process-your-bank-account-exports</id><content type="html" xml:base="https://balagetech.com/2025/01/07/introducing-whatsthedamage-to-process-your-bank-account-exports/"><![CDATA[<p>Introducing ‘<em>**</em><a href="https://github.com/abalage/whatsthedamage">whatsthedamage</a>’ - a tool to process your bank account exports. I share my journey of creating this tool in Python, the challenges I encountered, and how AI helped along the way.</p>

<p>Managing personal finances can be a bit of a headache, especially when it comes to turning bank account exports into useful reports.&lt;/</p>

<p>I found that many existing software options just didn’t meet my needs. Either they had high learning curves, like using double accounting, or having constant maintenance burden.</p>

<p>So, I decided to take matters into my own hands and develop a solution tailored to my specific needs. <a href="#verdict">Can an AI code assistant help me along the way?</a> Let’s find out!</p>

<h2 id="are-my-needs-really-special">Are my needs really special?</h2>

<p>There are dozens of fintech companies and software that promise to give you insights and other services once you give them access to your bank account details.</p>

<p>However, I consider my financial details to be a private matter between myself and my chosen bank. To process my bank account exports **I require a solution to process the data only I have access to. **This includes the exporting functionality of my internet bank to get historical data saved into CSV files.</p>

<p>Speaking of CSV exports, I have already tested <a href="https://www.firefly-iii.org/">Firefly III</a> which looked promising but requires you to know how double accounting works and to have data from all your accounts. I also found its rule engine a bit harder to use.&lt;/</p>

<p>I also tested <a href="https://actualbudget.org/">Actual Budget</a> which has a different concept. However, I found it harder to use for existing transaction histories. Especially when you want to have reports about transactions going back for years.</p>

<p>Should you quickly want to find out what <em>**</em><a href="https://github.com/abalage/whatsthedamage">whatsthedamage</a> is capable of, check the <a href="#whatsthedamage">introduction of “whatsthedamage”</a>.</p>

<h2 id="improve-python-skills-by-creating-software-from-scratch">Improve Python skills by creating software from scratch</h2>

<p>I have been using Python for a couple of years now to create scripts to automate stuff. Such as <a href="https://github.com/abalage/blocklist-firewalld">processing IP block lists to create firewalld rules</a>. Or a silly attempt to <a href="https://github.com/abalage/pods-compose">fill the gap between docker-compose and podman</a>. But I also wanted an open source project that I could proudly share with the audience. A tool to process your CSV bank account exports also might be useful for others.</p>

<h3 id="deliver-faster-by-using-an-ai-code-assistant">Deliver faster by using an AI code assistant</h3>

<p>I was somewhat frustrated that I had to write a complete software to process my CSV bank account exports. So I expected probably hours of googling and reading to know how to do stuff like static code analysis, writing test cases for Python or even how to package it. You may know that <strong>the first step is usually the hardest</strong>.</p>

<p>At the same time I was also curious whether can I use some AI code assistant to reduce the learning time and deliver faster. So I could just get started without the overwhelming feeling of investing a lot of resources upfront.</p>

<h3 id="specifying-high-level-requirements">Specifying high level requirements</h3>

<p>For getting what you want, you need to know what you want. High level designs are somewhat required. You need to have a clear picture of what you really expect from the tool. Here are my high level requirements.</p>

<ul>
  <li>
    <p>Work on CSV exports containing historical transactions, even going back for years.</p>
  </li>
  <li>
    <p>Categorize transactions into well known categories like purchases, transfers, deposits, etc.</p>
  </li>
  <li>
    <p>Add user defined categories like groceries, mortgage, cars, house maintenance, etc.</p>
  </li>
  <li>
    <p>Be able to categorize transactions based on user-defined regular expressions.</p>
  </li>
  <li>
    <p>Summarize amounts per categories.</p>
  </li>
  <li>
    <p>Filter transactions per interval.</p>
  </li>
  <li>
    <p>Provide results in a format which is easy to understand.</p>
  </li>
  <li>
    <p>Provide results in CSV format.</p>
  </li>
</ul>

<h3 id="specifying-low-level-requirements">Specifying low level requirements</h3>

<p>High-level requirements need to be translated into lower-level requirements. Even if I ask an AI service to create code for me I have to tell it what to do. So I broke down the high-level requirements into manageable pieces. Here are some examples below.</p>

<ul>
  <li>
    <p>Create a class called CsvFileReader that is responsible for reading a CSV file and storing the headers and rows separately.</p>
  </li>
  <li>
    <p>Each row in a CSV file should be a separate object in the CsvRow class, containing the row contents as key-value pairs using the keys from the headers.</p>
  </li>
  <li>
    <p>Use ‘argparse’ to set up command-line arguments for providing a filename that points to a CSV file.</p>
  </li>
  <li>
    <p>Create unit tests using pytest for the DateConverter class.</p>
  </li>
</ul>

<h2 id="introducing-whatsthedamage-to-process-your-bank-exports">Introducing “whatsthedamage” to process your bank exports</h2>

<p>Although the <a href="https://github.com/abalage/whatsthedamage">project’s GitHub page</a> contains a lot of information still I would like to highlight the main features it has.</p>

<ul>
  <li>
    <p><strong>Automated Categorization</strong>: Categorizes transactions into well-known accounting categories such as deposits and payments, as well as custom categories using regular expressions.</p>
  </li>
  <li>
    <p><strong>Filtering</strong>: Filter transactions by start and end dates, or group them by month for a comprehensive overview of your finances.</p>
  </li>
  <li>
    <p><strong>Detailed Reporting</strong>: Generate summarized reports that provide insights into your spending habits, grouped by transaction categories.</p>
  </li>
  <li>
    <p><strong>CSV Export</strong>: Save your reports as CSV files for easy sharing and further analysis.</p>
  </li>
  <li>
    <p>**Custom configuration: **Use custom configuration to use your own regular expressions.</p>
  </li>
</ul>

<p><a href="/assets/uploads/2025/01/whatsthedamage_filtered_report.png"><img src="/assets/uploads/2025/01/whatsthedamage_filtered_report.png" alt="whatsthedamage tool's filtered report" /></a></p>

<p><em>Filtered report from January and February</em></p>

<p>Install and usage instructions can be found on <a href="https://github.com/abalage/whatsthedamage">whatsthedamage’s project page</a>.</p>

<h3 id="what-about-the-maintenance-burden">What about the maintenance burden?</h3>

<p>I mentioned earlier that I was not really fond of the rules engines of Firefly III and Actual Budget. I do not want to reinvent the wheel and I want something which is easier to use, thus I opted for using regular expressions.</p>

<p>Does it solve all the problems of maintenance requirements the other tools have? Certainly no. Complexity has to live somewhere. :)</p>

<p>Is it better than the others? For me it is. Writing regexps is easier for me than creating a complex rule engine.</p>

<p>For people not experienced in writing regular expressions, I provide a <a href="https://github.com/abalage/whatsthedamage/blob/main/config.json.default">default configuration</a> having patterns for many well known retail chains available in Hungary.</p>

<h2 id="my-experiences-with-copilot-and-chatgpt">My experiences with Copilot and ChatGPT</h2>

<p>I mentioned earlier that most of the code in <a href="https://github.com/abalage/whatsthedamage">whatsthedamage</a> was created with the help of Copilot and ChatGPT. Either by directly creating code from scratch (like most of the unit tests and documentation), or iterating over codes written by me but asked Copilot to review it and possibly provide improvements.</p>

<p><em>At the time I am writing this post, both Copilot and ChatGPT (free tier) use the GPT-4o model.</em></p>

<h3 id="these-are-the-positive-remarks-i-made-during-the-development">These are the positive remarks I made during the development.</h3>

<ul>
  <li>
    <p>Some responses were surprisingly good and worked as is. There were even cases when it added functionalities I was just about to explicitly ask for. It was as if it were reading your mind. I am not kidding sometimes I even dropped my jaw.</p>
  </li>
  <li>
    <p>The learning speed by using “Explain” and in situations like “Show me how to achieve this specific task in pyproject.toml” was sometimes really overwhelming. Had I needed to Google it myself, it would have taken much longer.</p>
  </li>
</ul>

<h3 id="and-the-negative-remarks-i-experienced">And the negative remarks I experienced.</h3>

<ul>
  <li>
    <p>Adjustments made by AI on reviewed code blocks often resulted in lost comments or indentation problems.</p>
  </li>
  <li>
    <p>Suggestions to a problem sometimes contain the very same code that you asked the suggestion for. Line by line.</p>
  </li>
  <li>
    <p>If you argue with the AI about the suggestions, it will happily and politely suggest alternatives. But sometimes you realize that it goes round and round and does not really have much of a clue. In such cases usually adjusting the context could help.</p>
  </li>
</ul>

<h2 id="my-verdict-about-the-ai-code-assistant">My verdict about the AI code assistant</h2>

<p>I found using such a new kind of tool to complete my tasks fascinating and fun to work with. Although I admit that you need to have some level of coding knowledge about Python and programming in general to verify that what you got from the AI is really what you needed.</p>

<p>I do not think it is a silver bullet; however, it considerably helped me to understand new things in a quick and more focused format. Also its “pair programming” approach helped me to spot issues I did and learn new things faster.</p>

<p>After I was mostly done with this post, I ran into the article <a href="https://addyo.substack.com/p/the-70-problem-hard-truths-about">The 70% problem: Hard truths about AI-assisted coding</a> by Addy Osmani. Addy explains why junior and experienced developers use code assistants differently. I pretty much agree with him. You have to have some level of existing knowledge to use a code assistant effectively, but do not forget the “Trust but verify” pattern.</p>

<p>*Full disclosure: Microsoft Designer were used to create the picture for this blog, so as ChatGPT was used for proof reading. The python code were created with the help of Copilot.
*</p>]]></content><author><name>Balázs Németh</name></author><category term="script" /><category term="bank-account" /><category term="code-assistant" /><category term="csv" /><category term="python" /><summary type="html"><![CDATA[Introducing ‘**whatsthedamage’ - a tool to process your bank account exports. I share my journey of creating this tool in Python, the challenges I encountered, and how AI helped along the way.]]></summary></entry><entry><title type="html">Install Jellyfin server with Ansible</title><link href="https://balagetech.com/2024/02/21/install-jellyfin-server-with-ansible/" rel="alternate" type="text/html" title="Install Jellyfin server with Ansible" /><published>2024-02-21T21:27:11+00:00</published><updated>2024-02-21T21:27:11+00:00</updated><id>https://balagetech.com/2024/02/21/install-jellyfin-server-with-ansible</id><content type="html" xml:base="https://balagetech.com/2024/02/21/install-jellyfin-server-with-ansible/"><![CDATA[<p>Install Jellyfin server with Ansible to set up your own media streaming service in an automated manner. Download the role to install your own media server. This post does not explain Jellyfin itself, it is only about to install it with Ansible.</p>

<h2 id="why-install-jellyfin-server-with-ansible">Why install Jellyfin server with Ansible?</h2>

<p>I have a plan to rebuild all my self hosted services in an automated way by using Ansible. I looked for existing roles to install Jellyfin server with Ansible but most of them were not updated for a while or clearly relied on APT package manager. There is nothing wrong in using a Debian package repository, but I use OpenSUSE and at the time of writing this, there is no package repository for OpenSUSE. So I sticked to the <a href="https://jellyfin.org/docs/general/installation/linux#linux-generic-amd64">generic amd64 installer.</a></p>

<p>The role installs and starts the generic amd64 package on Linux. Sets up a systemd service which starts jellyfin automatically on boot.</p>

<h2 id="why-a-generic-package-and-not-docker-or-kubernetes">Why a generic package and not Docker or Kubernetes?</h2>

<p>That server I use is still <a href="/2023/06/15/running-home-assistant-on-kubernetes/">running Home Assistant on Kubernetes</a>. But passing tebibytes of data through some additional level of storage layer just to be able to connect it to a Jellyfin pod does not worth the effort at least performance wise.</p>

<h2 id="automate-the-automation">Automate the automation</h2>

<p>I wanted to publish the role on <a href="https://galaxy.ansible.com/ui/standalone/roles/abalage/jellyfin/">Ansible Galaxy</a> but also in an automated way by using GitHub Actions. I’ve been using GitLab for a while so I already familiar with the concept of CI/CD pipelines. I only needed to get around the syntax GitHub uses.</p>

<h3 id="tasks-i-automated-by-using-github-actions">Tasks I automated by using GitHub Actions</h3>

<ol>
  <li>
    <p>First of all there are lint tests by using <a href="https://pypi.org/project/yamllint/">yamllint</a> and <a href="https://pypi.org/project/ansible-lint/">ansible-lint</a> to look for possible issues introduced by typos or bad usage patterns. That’s really basic but are very helpful.</p>
  </li>
  <li>
    <p>I utilize <a href="https://pypi.org/project/molecule/">Molecule</a> framework to test the Ansible role itself. Molecule itself is not a static code analysis tool like yamllint. It tests all tasks by actually executing them in a sandbox environment. You can even spot idempotent issues for example.
It is always a best practice to make sure you write idempotent tasks.
However I admit that sometimes fixing those are either impossible or simply does not worth the effort.</p>
  </li>
  <li>
    <p>The third chunk of the workflow is to upload a release of the role once a commit is tagged in git. This makes releasing easy and less prone to errors.</p>
  </li>
</ol>

<p>I remember I used to release manually when I developed an Ansible collection to <a href="/2021/12/06/deploy-elasticsearch-stack-with-podman-and-ansible/">deploy Elasticsearch stack with podman and ansible</a>. But that’s the past.</p>

<h2 id="how-to-use-the-ansible-role">How to use the Ansible role</h2>

<p>I assume you already have an <a href="https://docs.ansible.com/ansible/latest/inventory_guide/intro_inventory.html">Ansible inventory</a> file.
You need a playbook to invoke the role. The sample <a href="https://github.com/abalage/ansible-role-jellyfin?tab=readme-ov-file#example-playbook">playbook.yml</a> I provided next to the <a href="https://github.com/abalage/ansible-role-jellyfin">abalage.jellyfin</a> role works just fine.</p>

<p>You also need a <strong>roles/requirements.yaml</strong> file to contain the source of the role. Get the latest and greatest version directly from the git repo like this.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>roles:
  - name: abalage.jellyfin
    src: https://github.com/abalage/ansible-role-jellyfin.git
    version: main
</code></pre></div></div>

<p>Or fetch the versioned role from Ansible Galaxy.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>roles:
  - name: abalage.jellyfin
    version: 1.0.1
</code></pre></div></div>

<p>Once that is ready you can get it by using ansible-galaxy and install it by using ansible-playbook.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ansible-galaxy role install --force -r roles/requirements.yml
$ ansible-playbook -i inventory.ini playbook.yml
</code></pre></div></div>

<p>The role is open source. Feel free to use it.
Should you any feedback please leave in the comments below.</p>

<p>Disclaimer: the featured image in this post was created by AI.</p>]]></content><author><name>Balázs Németh</name></author><category term="automation" /><category term="entertainment" /><category term="ansible" /><summary type="html"><![CDATA[Install Jellyfin server with Ansible to set up your own media streaming service in an automated manner. Download the role to install your own media server. This post does not explain Jellyfin itself, it is only about to install it with Ansible.]]></summary></entry><entry><title type="html">Running Home Assistant on Kubernetes</title><link href="https://balagetech.com/2023/06/15/running-home-assistant-on-kubernetes/" rel="alternate" type="text/html" title="Running Home Assistant on Kubernetes" /><published>2023-06-15T21:33:24+00:00</published><updated>2023-06-15T21:33:24+00:00</updated><id>https://balagetech.com/2023/06/15/running-home-assistant-on-kubernetes</id><content type="html" xml:base="https://balagetech.com/2023/06/15/running-home-assistant-on-kubernetes/"><![CDATA[<p>Running Home Assistant on Kubernetes. It is about time to put your IoT devices under control. Everything runs off the cloud on my on-premise Kubernetes. Clean and secure.</p>

<p>This blog will not cover what <a href="https://www.home-assistant.io">Home Assistant</a> is or <a href="https://kubernetes.io/docs/concepts/">how Kubernetes works</a>. I assume you already have that covered.</p>

<h2 id="separate-network-traffic-for-iot-devices">Separate network traffic for IoT devices</h2>

<p>I created a separate VLAN just for IoT devices on my OpenWRT. Some things to notice about this VLAN.</p>

<ul>
  <li>
    <p>A separate AP exists for devices communicating over WiFi.</p>
  </li>
  <li>
    <p>This VLAN does have access neither to other networks nor to the Internet. So no IoT device will be able to <a href="/2019/04/27/android-app-phones-home-china/">phone home</a>. And most probably you cannot use the official Apps.</p>
  </li>
  <li>
    <p>Kubernets has a dedicated <a href="https://kubernetes.github.io/ingress-nginx/">Nginx Ingress Controller</a> listening in this VLAN, opposite to the <a href="https://docs.k3s.io/networking#traefik-ingress-controller">Traefik Ingress Controller</a> which listens in the default network.</p>
  </li>
  <li>
    <p>The host running Kubernetes does have a network connection in both VLANs (optional).</p>
  </li>
</ul>

<p>If you would like to create VLANs but don’t know how to start I highly recommend watching Mark’s great video about <a href="https://www.youtube.com/watch?v=qeuZqRqH-ug">VLANs in OpenWrt 21</a>. It will give you a head start.</p>

<h2 id="use-k3s-lightweight-kubernetes-distribution-for-iot">Use K3s lightweight Kubernetes distribution for IoT</h2>

<p>Although there are many Kubernetes distributions to choose from, I have picked <a href="https://k3s.io/">K3s</a>.</p>

<p>It is a lightweight Kubernetes and it is proven to work on a bunch of <del>inexpensive</del> unavailable Raspberry Pi4s running in a basement just like <a href="https://www.jeffgeerling.com/project/raspberry-pi-dramble">Jeff’s Pi Dramble</a>. Make sure to check him out, it is unbelievable. :)</p>

<h2 id="the-deployment-problem-of-home-assistant">The Deployment problem of Home Assistant</h2>

<p>There are a couple of supported ways of <a href="https://www.home-assistant.io/installation/">installing Home Assistant</a>. Unfortunately Kubernetes is not among them. I do not blame them. Probably it simply does not worth the effort to support it, because people using Home Assistant is already a niche market, even more people running Kubernetes at home.</p>

<p>There are 4 options to install it.</p>

<ul>
  <li>
    <p>Home Assistant Operating System - their own operating system based on Docker (no go)</p>
  </li>
  <li>
    <p>Home Assistant Container - A container image containing only the core of Home Assistant (we’ll use this)</p>
  </li>
  <li>
    <p>Home Assistant Supervised - <em>“This way of running Home Assistant will require the most of you. It also has strict requirements you need to follow.”</em> (still requires Docker’s socket - no go)</p>
  </li>
  <li>
    <p>Home Assistant Core - Same as <em>Home Assistant Container</em> but without the container (no go)</p>
  </li>
</ul>

<p>The biggest drawback of using their container image is that there will be no “<a href="https://www.home-assistant.io/addons/">Addons store</a>” feature. And you will need to find the necessary howtos in forums, github issues, etc.</p>

<p>So I will rely on their container image but what about deployment descriptions?</p>

<p>I cannot really use their docker-compose.yml in Kubernetes for other purposes than as a base for creating my own manifests.</p>

<p>There were Helm charts available for some time but at the time of writing this article, none of them are maintained anymore but at least they are better source for creating something new than using the docker-compose YMLs. I decided to roll my own version of manifest and keeping things as simple as possible.</p>

<h2 id="installing-home-assistant-with-kustomize">Installing Home Assistant with Kustomize</h2>

<p>So I have the official container image but I will need services other than the plain Core of Home Assistant. I need the following functionalities.</p>

<ul>
  <li>
    <p>Home Assistant itself. You can grab the Kubernetes manifest from <a href="https://github.com/abalage/home-assistant-k8s">abalage/home-assistant-k8s</a>.</p>
  </li>
  <li>
    <p>MQTT support (<a href="https://mosquitto.org/">Mosquitto</a>) which is a frequently required integration interface for lots of IoT devices. You can download the Kubernetes manifest from <a href="https://github.com/abalage/mosquitto-mqtt-k8s">abalage/mosquitto-mqtt-k8s</a>.</p>
  </li>
  <li>
    <p><a href="https://kubernetes.github.io/ingress-nginx/">Nginx Ingress Controller</a> to expose HTTP(s) and MQTT’s TCP port 1883 (later one is not HTTP protocol)</p>
  </li>
  <li>
    <p><a href="https://github.com/metallb/metallb">MetalLB</a> for acquiring an externally addressable IP address for Home Assistant’s service (LoadBalancer)</p>
  </li>
</ul>

<p>Like I mentioned before the Helm charts are outdated and I needed some customization anyway,  hence I use <a href="https://kustomize.io/">Kustomize</a> to get all the dependencies properly configured and patched to fit my network environment.</p>

<p><strong>You do not need to individually download the manifests. Just check out the GitHub project <a href="https://github.com/abalage/Home-Assistant-on-Kubernetes">abalage/Home-Assistant-on-Kubernetes</a> which contains everything you need to start.</strong></p>

<p>Make sure you edit `kustomization.yaml` to fit to your environment. Check out the README for details.</p>

<p>Now you can run your own Home Assistant on Kubernetes.</p>

<p>What do you think? Isn’t it awesome? :)</p>]]></content><author><name>Balázs Németh</name></author><category term="automation" /><category term="kubernetes" /><category term="security" /><category term="ansible" /><category term="diy_home_server" /><category term="kubernetes" /><summary type="html"><![CDATA[Running Home Assistant on Kubernetes. It is about time to put your IoT devices under control. Everything runs off the cloud on my on-premise Kubernetes. Clean and secure.]]></summary></entry><entry><title type="html">Deploy Elasticsearch stack with podman and Ansible</title><link href="https://balagetech.com/2021/12/06/deploy-elasticsearch-stack-with-podman-and-ansible/" rel="alternate" type="text/html" title="Deploy Elasticsearch stack with podman and Ansible" /><published>2021-12-06T22:03:43+00:00</published><updated>2021-12-06T22:03:43+00:00</updated><id>https://balagetech.com/2021/12/06/deploy-elasticsearch-stack-with-podman-and-ansible</id><content type="html" xml:base="https://balagetech.com/2021/12/06/deploy-elasticsearch-stack-with-podman-and-ansible/"><![CDATA[<p>Deploy Elasticsearch stack with podman and Ansible. Halfway on the road towards complete automation. But without the necessity of a complex orchestration tool. Somewhere between <a href="https://www.hava.io/blog/cattle-vs-pets-devops-explained">pets and cattles</a>.</p>

<p>There is an existing Ansible collection <a href="https://galaxy.ansible.com/containers/podman">containers.podman</a> to handle podman pods and containers. Although Elastic the company already maintains an <a href="https://github.com/elastic/ansible-elasticsearch">Ansible playbook for Elasticsearch</a>, it uses regular Linux packages and not container images. Meet <a href="https://galaxy.ansible.com/abalage/elasticstack_podman">abalage.elasticstack_podman</a> a collection of Ansible roles to deploy and handle an Elasticsearch cluster and its components like Kibana, Filebeat, Metricbeat and Logstash.</p>

<p>You can download it from <a href="https://galaxy.ansible.com/abalage/elasticstack_podman">galaxy.ansible.com</a> or from <a href="https://github.com/abalage/ansible_collection_elasticstack_podman">github</a>.</p>

<h2 id="requirements">Requirements</h2>

<p>Any operating system which supports a relatively recent version of podman (&gt;=3.0) is required. Beware that CentOS 7 is not among them. The playbooks were tested on AlmaLinux 8.4 and OpenSUSE Leap 15.3. However on OpenSUSE you need to use a third party repository (<a href="https://build.opensuse.org/project/show/Virtualization:containers">Virtualization_containers</a>).</p>

<p>The collection does not contain a reverse proxy for Kibana. You can use either Traefik of NGINX. The Kibana container is <a href="https://github.com/abalage/ansible_collection_elasticstack_podman/blob/e9bedff52dd5c49c58d97859d2d3361297f2e034/roles/kibana/tasks/kibana_podman.yml#L43">already provides labels</a> for Traefik.</p>

<h2 id="features">Features</h2>

<p>I implemented the following features.</p>

<ul>
  <li>
    <p>It deploys an Elasticsearch cluster. Works with single node deployments. However you can build a cluster of multiple nodes as well. You can even run multiple nodes on the same host OS.</p>
  </li>
  <li>
    <p>Use Kibana for visualization.</p>
  </li>
  <li>
    <p>Metricbeat automatically collects and stores all components metrics in the cluster. Use Kibana’s <em>Stack Monitoring</em> app to access the metrics.</p>
  </li>
  <li>
    <p>Filebeat sends the components logs to Elasticsearch. Use Kibana’s <em>Logs</em> app to access the logs.</p>
  </li>
  <li>
    <p>Optionally you can set up Logstash containers too. Although there are not many pipeline templates available.</p>
  </li>
  <li>
    <p>Automatically populates built-in and custom users, passwords and roles. It does not support AD integration yet.</p>
  </li>
  <li>
    <p>Pods and containers are automatically started upon reboot by using systemd units.</p>
  </li>
  <li>
    <p>Supports host firewalld. Disabled by default.</p>
  </li>
  <li>
    <p>Works best with <a href="https://podman.io/getting-started/network.html">host networking</a>. Support for bridge networking is best effort and has scalability limitations. It does not support rootless networking at the moment.</p>
  </li>
</ul>

<h2 id="usage-of-the-collection">Usage of the collection</h2>

<p>I expect you already have an Ansible control node and several managed hosts. The collection was developed and tested with Ansible 2.9.</p>

<h3 id="create-your-deployment-playbook">Create your deployment playbook</h3>

<p>A playbook defines which play, roles and tasks of the collection are executed on which hosts. There is an existing playbook called <a href="https://github.com/abalage/elk-podman-deployment">elk-podman-deployment</a> you can use. For example there is an <a href="https://github.com/abalage/ansible_collection_elasticstack_podman/blob/main/example/playbook/playbook.yml">example playbook</a> in the repository too.</p>

<h3 id="create-your-deployment-inventory">Create your deployment inventory</h3>

<p>The deployment inventory describes how your cluster looks like. You can use the variables from the role’s defaults to create an inventory form scratch. However I provide a <a href="https://github.com/abalage/ansible_collection_elasticstack_podman/blob/main/example/playbook/playbook.yml">example inventory</a> that you can customize.</p>

<p>Do not forget to encrypt sensitive data with ansible-vault.</p>

<p>I highly recommend to create proper X.509 certificates for TLS for security reasons. Make sure to follow the <a href="https://github.com/abalage/ansible_collection_elasticstack_podman#securing-elasticsearch-cluster">Securing Elasticsearch cluster</a> guide to create such certificates.</p>

<h3 id="run-the-playbook">Run the playbook</h3>

<p>Once the inventory is complete, you can run the playbook like this tot deploy Elasticsearch stack with podman and Ansible.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ ansible-playbook -i /path/to/production.ini playbook.yml --vault-password-file /path/to/vault-secret 
</code></pre></div></div>

<p>It is a good idea to run in check mode on the first run to see whether is there anything missing from the inventory.</p>

<h3 id="reverse-proxy">Reverse proxy</h3>

<p>The collection itself does not provide any reverse proxy.</p>

<p>You can use any kind of reverse proxy to provide access to Kibana or any other components. I suggest to use Traefik for auto-discovery.</p>

<h2 id="conclusion">Conclusion</h2>

<p>Developing all these roles and task were fun. I could learn a lot about Ansible. Therefore I can recommend this collection to anyone who would need such a setup but without the requirement of having a complex orchestration platform. I am aware of production systems deployed by this playbook.</p>

<p>However. I think this approach on the long run is not feasible. The architecture can grow to became uncontrolled pretty easily, unless someone constantly maintains the collection and provides support.</p>

<p>I could think of better alternatives like incorporating the container parts into Elastic’s official Ansible playbook. So the support would come from the vendor and not from the community. It might also worth to try some Edge/IoT oriented Kubernetes distribution like K3s which is lightweight but also supports <a href="https://cloud.redhat.com/blog/build-kubernetes-operators-from-helm-charts-in-5-steps">Helm charts or better Operators</a>.</p>

<p>What do you think?</p>]]></content><author><name>Balázs Németh</name></author><category term="automation" /><category term="script" /><category term="ansible" /><category term="elasticsearch" /><category term="kibana" /><category term="podman" /><summary type="html"><![CDATA[Deploy Elasticsearch stack with podman and Ansible. Halfway on the road towards complete automation. But without the necessity of a complex orchestration tool. Somewhere between pets and cattles.]]></summary></entry><entry><title type="html">Install OpenSUSE MicroOS in KVM with Ignition</title><link href="https://balagetech.com/2020/04/23/install-opensuse-microos-kvm-ignition/" rel="alternate" type="text/html" title="Install OpenSUSE MicroOS in KVM with Ignition" /><published>2020-04-23T21:44:07+00:00</published><updated>2020-04-23T21:44:07+00:00</updated><id>https://balagetech.com/2020/04/23/install-opensuse-microos-kvm-ignition</id><content type="html" xml:base="https://balagetech.com/2020/04/23/install-opensuse-microos-kvm-ignition/"><![CDATA[<p>Install <a href="https://en.opensuse.org/Kubic:Installation#Installation">OpenSUSE MicroOS</a> in KVM with Ignition. A step-by-step guide to provision container specific OS instances really fast.</p>

<h2 id="about-opensuse-microos">About OpenSUSE MicroOS</h2>

<p>I needed a container specific OS since I <a href="/2020/02/10/convert-docker-compose-services-to-pods/">converted my docker-compose services to pods with Podman</a>. Fedora CoreOS looks promising. However I have been using OpenSUSE for years, so it was convenient for me to try <a href="https://en.opensuse.org/Kubic:MicroOS">MicroOS</a> which is derived from Tumbleweed.</p>

<p>These are the features which I like the most.</p>

<ul>
  <li>
    <p>Automatic transactional updates. If you do not like the result, then you can switch back to the previous snapshot.</p>
  </li>
  <li>
    <p>Up to date software versions. Especially for software like <a href="/2020/03/31/managing-podman-pods-with-pods-compose/">Podman</a> which improves rapidly.</p>
  </li>
  <li>
    <p><a href="https://www.youtube.com/watch?v=nIwqzGbX-oc">A minimal environment specially designed for container workloads.</a> It has greatly reduced attack surfaces and improved performance.</p>
  </li>
</ul>

<h2 id="install-opensuse-microos-in-kvm-with-ignition">Install OpenSUSE MicroOS in KVM with Ignition</h2>

<p>There are documentations about MicroOS, but I could not find a complete guide about how to install OpenSUSE MicroOS in KVM. Also its Ignition guide directly redirects to CoreOS’s git repo for documentation. The information is there but putting it together takes time. <br />
As I already managed to do it then why not to share it? :)</p>

<p>In my guide I will use virsh (<a href="https://libvirt.org/">libvirt</a>) and virt-install (<a href="https://virt-manager.org/">virt-manager</a>) to provision headless MicroOS VMs based on the downloadable KVM images they made available. Both tools are higher lever APIs to KVM / QEMU.</p>

<h3 id="installing-libvirt-to-make-using-qemu-easy">Installing libvirt to make using QEMU easy</h3>

<p>OpenSUSE has a package pattern for turning your OS into a virtualization host. Following the <a href="https://doc.opensuse.org/documentation/leap/virtualization/html/book.virt/cha-vt-installation.html#sec-vt-installation-kvm">Virtualization Guide</a> will definitely help. But if you do not want to read it all then just run the following command.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>zypper in -t pattern kvm_server kvm_tools
</code></pre></div></div>

<p>Should you want to read more about <a href="https://doc.opensuse.org/documentation/leap/virtualization/html/book.virt/part-virt-libvirt.html">managing virtual machines with libvirt</a> then there is a documentation for that too. I will not go into details this time.</p>

<h3 id="downloading-and-verify-installation-media-of-microos">Downloading and verify installation media of MicroOS</h3>

<p>Once the tools are ready then download the installation media and verify the checksum and <a href="https://en.opensuse.org/SDB:Download_help">signature</a>.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># cd /var/lib/libvirt/images
# curl -LO http://download.opensuse.org/tumbleweed/appliances/openSUSE-MicroOS.x86_64-ContainerHost-kvm-and-xen.qcow2
# curl -LO http://download.opensuse.org/tumbleweed/appliances/openSUSE-MicroOS.x86_64-ContainerHost-kvm-and-xen.qcow2.sha256
# curl -LO http://download.opensuse.org/tumbleweed/appliances/openSUSE-MicroOS.x86_64-ContainerHost-kvm-and-xen.qcow2.sha256.asc
</code></pre></div></div>

<p>Note that sha256 checksum and signature was made for a snapshot whose name is different from the file we downloaded, though the content is the same. Probably the other files on their webserver are just symbolic links.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># sha256sum openSUSE-MicroOS.x86_64-ContainerHost-kvm-and-xen.qcow2
# gpg --search-keys B88B2FD43DBDC284
# gpg --recv-keys 0x22C07BA534178CD02EFE22AAB88B2FD43DBDC284
# gpg --verify openSUSE-MicroOS.x86_64-ContainerHost-kvm-and-xen.qcow2.sha256.asc
</code></pre></div></div>

<h3 id="creating-ignition-configuration-for-vm">Creating Ignition configuration for VM</h3>

<p>Ignition expect its configuration to be in JSON. <a href="https://docs.fedoraproject.org/en-US/fedora-coreos/producing-ign/">However one just not create a JSON file by hand</a>. But creates a YML file and convert it with semantic checks (and some boilerplate) to JSON by using CoreOS’s <a href="https://docs.fedoraproject.org/en-US/fedora-coreos/fcct-config/">fcct</a>. Here is my example. It is pretty straight forward.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>variant: fcos
version: 1.0.0
passwd:
  users:
    - name: root
      ssh_authorized_keys:
        - ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDHj2D8PAxz0MKV9UJ8dxavlVzdAvMBrfGp38sj4q/aRbkcuYVNHAQh+xXHI0VcPEtu9rqZbvqfmQt0DFhsdf938W6r3y6mLp4+6KIDgb4Jj2B3zlzBIF0haAFi/GZAp4dh4uuhHsVvZGqsdqCglxUnIPb+i8IyYA8GGU+3IOgRfjjtpMfDJcWZTzGm56yDsBYORX3EckkGcWTN4/oW0SKWoO9zf/887/CvVZF/0V7corEAdMyTCiSSqqUjIDLAZpCMU4czadZop7cvVjGT6WLmyGDuTBruvjsMwxYA/OMAZrUuOEoAW0bf/QZRZ4tO7ku+o0oqwca5uwVbuouAFovJ root@example
      password_hash: "$1$salt$qJH7.N4xYta3aEG/dfqo/0"
storage:
  files:
    - path: /etc/sysconfig/network/ifcfg-eth0
      mode: 0600
      overwrite: true
      contents:
        inline: |
          BOOTPROTO='static'
          STARTMODE='auto'
          BROADCAST=''
          ETHTOOL_OPTIONS=''
          IPADDR='192.168.0.10/24'
          MTU=''
          NAME=''
          NETWORK=''
          REMOTE_IPADDR=''
          ZONE=public
    - path: /etc/sysconfig/network/routes
      mode: 0644
      overwrite: true
      contents:
        inline: |
          default 192.168.0.254 - -
    - path: /etc/hostname
      mode: 0644
      overwrite: true
      contents:
        inline: |
          example.com
</code></pre></div></div>

<p>Please note that on OpenSUSE you cannot just provide static DNS information by overwriting /etc/resolv.conf. Because the <a href="https://www.suse.com/c/configure-netconfig-static-domain-search-lists/">content of /etc/resolv.conf is managed by netconfig</a>. And it configuration file bigger than optimal to include it in a YML file. Though you can configure it manually after the first run.</p>

<p>Once you are ready, put the contents into config.fcc and convert it to JSON by using fcct.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># podman run -i --rm quay.io/coreos/fcct:release --pretty --strict &lt; config.fcc &gt; config.ign
</code></pre></div></div>

<h3 id="create-a-kvm-host-with-virt-install">Create a KVM host with virt-install</h3>

<p>The Ignition file can be specified via QEMU command line. Adjust the specification of the VM according to your needs.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># virt-install --import --connect qemu:///system --name example \
    --ram 1024 --vcpus 1 \
    --disk size=20,backing_store=/var/lib/libvirt/images/openSUSE-MicroOS.x86_64-ContainerHost-kvm-and-xen.qcow2,bus=virtio \
    --os-variant=opensusetumbleweed \
    --network bridge=br0,model=virtio \
    --noautoconsole \
    --graphics spice,listen=127.0.0.1 \
    --qemu-commandline="-fw_cfg name=opt/com.coreos/config,file=/path/to/config.ign"
</code></pre></div></div>

<p>No you have just installed OpenSUSE<span class="has-inline-color has-blue-color"> MicroOS in KVM with Ignition. </span>Enjoy.</p>

<h2 id="managing-vm-with-virsh">Managing VM with Virsh</h2>

<p>Virsh is another tool to manage your VMs. Here I provide some examples I frequently use. They could be useful.</p>

<h3 id="console-access">Console access</h3>

<p>You can attach to the serial console of the VM with the following command.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># virsh console example
</code></pre></div></div>

<p><a href="https://www.cyberciti.biz/faq/howto-exit-virsh-console-connection-on-centos-ubuntu-debian-linux/">Disconnecting from Virsh console</a> is possible with SHIFT+5.</p>

<h3 id="remote-console-access">Remote console access</h3>

<p>Remote access to the console is possible with <a href="https://www.spice-space.org/index.html">Spice</a>. If you are not in production then you can easily <a href="https://unix.stackexchange.com/questions/148794/how-to-create-kvm-guest-with-spice-graphics-but-tls-disabled-using-virt-install">access the remote Spice port without TLS</a> via SSH port forward.</p>

<h3 id="delete-virtual-machines">Delete virtual machines</h3>

<p>This can be useful when you are not satisfied with the result and want to start over from scratch. <a href="https://www.cyberciti.biz/faq/howto-linux-delete-a-running-vm-guest-on-kvm/">Storage files are not automatically deleted</a>.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># virsh dumpxml --domain example | grep 'source file'
      &lt;source file='/var/lib/libvirt/images/example.qcow2'/&gt;
        &lt;source file='/var/lib/libvirt/images/openSUSE-MicroOS.x86_64-ContainerHost-kvm-and-xen.qcow2'/&gt;
# virsh destroy example
# virsh undefine example
# rm -f /var/lib/libvirt/images/example.qcow2
</code></pre></div></div>

<p>I hope you will enjoy your shiny new container host. :)</p>]]></content><author><name>Balázs Németh</name></author><category term="automation" /><category term="tutorials" /><category term="opensuse" /><category term="podman" /><summary type="html"><![CDATA[Install OpenSUSE MicroOS in KVM with Ignition. A step-by-step guide to provision container specific OS instances really fast.]]></summary></entry><entry><title type="html">Managing Podman pods with pods-compose</title><link href="https://balagetech.com/2020/03/31/managing-podman-pods-with-pods-compose/" rel="alternate" type="text/html" title="Managing Podman pods with pods-compose" /><published>2020-03-31T22:08:15+00:00</published><updated>2020-03-31T22:08:15+00:00</updated><id>https://balagetech.com/2020/03/31/managing-podman-pods-with-pods-compose</id><content type="html" xml:base="https://balagetech.com/2020/03/31/managing-podman-pods-with-pods-compose/"><![CDATA[<p>Managing Podman pods with pods-compose makes your move to Podman easier. I already <a href="/2020/02/10/convert-docker-compose-services-to-pods/">converted my docker-compose services to pods with Podman</a>, however I really missed some features, up until now. Let’s meet <a href="https://github.com/abalage/pods-compose">pods-compose</a>.</p>

<h2 id="missing-features-of-podman">Missing features of Podman</h2>

<p>As soon as I managed to <a href="/2020/02/10/convert-docker-compose-services-to-pods/">convert docker-compose services to pods</a> I realized that managing them will be not as easy as it was with docker-compose. I faced with the following problems.</p>

<ol>
  <li>
    <p><strong>There is no autostart for pods and containers.</strong> Of course you can generate systemd service units for all components but managing them is not easy without an automation tool. There are separate service files for each pod and container.</p>
  </li>
  <li>
    <p><strong>For updates you might have to stop, remove, recreate everything from scratch, unless you script it.</strong> There is no ‘<em>up</em>’, ‘<em>down</em>’ or ‘<em>build</em>’ features like you have with docker-compose.</p>
  </li>
  <li>
    <p><strong>There is no single point of configuration which I could use to describe all the pods and containers.</strong> I could write and maintain Kubernetes YAML files, but that’s even harder than using the CLI syntax I am already familiar with.</p>
  </li>
</ol>

<p>I needed a tool which makes managing Podman pods easier. <a href="https://github.com/containers/podman-compose">podman-compose</a> looked promising but it did not really work for me and I also did not like its CLI interface. So I decided to write <a href="https://github.com/abalage/pods-compose">my own tool</a>.</p>

<h2 id="design-goals-of-pods-compose">Design goals of pods-compose</h2>

<p>I did not want to put a lot of effort into this. I only wanted the following additional abilities.</p>

<ul>
  <li>
    <p>Be able to automatically start and stop all pods and containers upon reboot.</p>
  </li>
  <li>
    <p>Tear down existing pods at once.</p>
  </li>
  <li>
    <p>Create pods and containers from a description at once.</p>
  </li>
  <li>
    <p>Build all the images I define with a single command.</p>
  </li>
</ul>

<p>I did not want to rely on docker-compose’s YAML format. Intentionally there is no support for using an existing compose configuration. Although I was already familiar with that format, I wanted a complete migration not just a partial one.</p>

<h2 id="managing-podman-pods-with-pods-compose">Managing Podman pods with pods-compose</h2>

<p>As a kickstart, let’s get a glimpse into the similarities between pods-compose and docker-compose.</p>

<table>
  <thead>
    <tr>
      <th> </th>
      <th><strong>pods-compose</strong></th>
      <th><strong>docker-compose</strong></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Deploy pod(s)</td>
      <td>–up [POD]</td>
      <td>up [SERVICE]</td>
    </tr>
    <tr>
      <td>Tear down pod(s)</td>
      <td>–down [POD]</td>
      <td>down [SERVICE]</td>
    </tr>
    <tr>
      <td>Start pod(s)</td>
      <td>–start [POD]</td>
      <td>start [SERVICE]</td>
    </tr>
    <tr>
      <td>Stop pod(s)</td>
      <td>–stop [POD]</td>
      <td>stop [SERVICE]</td>
    </tr>
    <tr>
      <td>Restart pod(s)</td>
      <td>–restart [POD]</td>
      <td>restart [SERVICE]</td>
    </tr>
    <tr>
      <td>Build all container images</td>
      <td>–build</td>
      <td>build</td>
    </tr>
    <tr>
      <td>Status of pods and containers</td>
      <td>–ps</td>
      <td>ps</td>
    </tr>
    <tr>
      <td>Generate Kubernetes Pod YAML(s)</td>
      <td>–generate</td>
      <td> </td>
    </tr>
  </tbody>
</table>

<h2 id="autostart-pods-and-containers">Autostart pods and containers</h2>

<p>Podman can generate systemd units for pods and containers. However there will be many of them, making it hard to overview and maintain it. Because pods-compose takes care of starting and stopping pods with a single command line option, I could create a single systemd service file instead of many.</p>

<p>The install script will deploy that systemd service file for pods-compose. Enabling it makes your pods and containers to start automatically upon reboot. And of course gracefully stop before the system halts.</p>

<p>Further details can be found in the <a href="https://github.com/abalage/pods-compose/blob/master/README.md">readme of pods-compose</a>.</p>

<h2 id="things-you-still-have-to-do-manually">Things you still have to do manually</h2>

<p>Creating containers at least first time is a manual procedure. People usually start with ‘docker run’ commands then once the result looks okay then will create a docker-compose YAML.</p>

<p>This will not change with pods-compose. You still have to create your pods and containers with ‘podman run’. <strong>However you do not have to create any YAML files.</strong> The tool will create them for you. <br />
Luckily <a href="https://podman.io/whatis.html">podman CLI syntax is almost the same as docker’s</a>, so it is easy to make progress fast.</p>

<p>The other part is defining which image should be built by pods-compose. Because this information cannot be set in Kubernetes YAML files, you can use <a href="https://github.com/abalage/pods-compose">pods-compose</a>’s INI formatted configuration file to define the TAG and the CONTEXT of images. As a result, pods-compose will build all the images for you.</p>

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

<p>Let me know if you are still missing some features you would love to see implemented in pods-compose. Also please share if you liked it.</p>]]></content><author><name>Balázs Németh</name></author><category term="script" /><category term="tutorials" /><category term="linux" /><category term="podman" /><category term="python" /><summary type="html"><![CDATA[Managing Podman pods with pods-compose makes your move to Podman easier. I already converted my docker-compose services to pods with Podman, however I really missed some features, up until now. Let’s meet pods-compose.]]></summary></entry><entry><title type="html">Convert docker-compose services to pods with Podman</title><link href="https://balagetech.com/2020/02/10/convert-docker-compose-services-to-pods/" rel="alternate" type="text/html" title="Convert docker-compose services to pods with Podman" /><published>2020-02-10T14:18:20+00:00</published><updated>2020-02-10T14:18:20+00:00</updated><id>https://balagetech.com/2020/02/10/convert-docker-compose-services-to-pods</id><content type="html" xml:base="https://balagetech.com/2020/02/10/convert-docker-compose-services-to-pods/"><![CDATA[<p>How to deploy pods with Podman when you only need a single-host system and not a complex Kubernetes. Convert your docker-compose services to pods with Podman.</p>

<p>For a single host setup or even for <a href="https://www.reddit.com/r/docker/comments/es1kxr/future_of_docker_swarm/">a now officially dead</a> Docker Swarm setup using docker-compose is pretty convenient. But I wanted to get rid of Docker completely and migrate my docker-compose services to pods with Podman.</p>

<h2 id="the-reasons-why-i-convert-docker-compose-services-to-pods">The reasons why I convert docker-compose services to pods</h2>

<p>I have been using Docker’s container technology for about 4-5 years. Both in production and in different labs. Call me an old fashioned but I always managed to set up systems either with pure Docker containers or with docker-compose. However there are things I cannot easily forget.</p>

<p>Here are the top reasons why I decided to convert my docker-compose services to pods with Podman and get rid of Docker completely.</p>

<ul>
  <li>
    <p>Closing issues with an attitude of ‘we don’t really care’. Like <a href="https://github.com/docker/compose/issues/4513">#4513</a>, or <a href="https://github.com/moby/moby/issues/22920#issuecomment-264036710">#22920#issuecomment-264036710</a></p>
  </li>
  <li>
    <p>Leaving important security requests open for years. Like <a href="https://github.com/docker/compose/issues/3480#issuecomment-482587531">#3480#issuecomment-482587531</a>.</p>
  </li>
  <li>
    <p>Recurring errors like failing to create many bridged network at once on a clean system, claiming ‘<em>ERROR: Pool overlaps with other one on this address space</em>’.</p>
  </li>
  <li>
    <p>Too many fiddling with iptables rules on a system using firewalld. This may not be a problem where a host OS’ only role is to run containers. But there are legit cases where containers may run on a host serving other purposes as well.</p>
  </li>
  <li>
    <p>Daemon changes causing data losses. I learned the hard way why putting a production SQL database (state-full) into a container is a NO GO.</p>
  </li>
  <li>
    <p>Inconsistency between recommendations and real life experience. Like “<strong>Don’t run more than one process in a single container</strong>” - Have you seen GitLab’s official <a href="https://docs.gitlab.com/omnibus/docker/">Docker image</a>?</p>
  </li>
  <li>
    <p>Various issues with logging. Some of them are already explained in posts like <a href="https://dzone.com/articles/top-10-docker-logging-gotchas">top 10 Docker logging gotchas</a>.</p>
  </li>
</ul>

<p>I know some of these reasons may not apply to recent versions of Docker. And I am also aware that some issues are container technology related, so they may apply to Podman containers as well.</p>

<h2 id="the-basis-of-migration">The basis of migration</h2>

<p>Any migration requires planning and testing. So I started off with my home lab which hosts different systems. In my lab docker-compose took care of composing all services with a single YAML file. The following simplified figure shows a high level overview of the network architecture. Although the picture may indicate, the reverse proxy is not the gateway for the containers.</p>

<figure class="wp-block-image size-large">
  <p><a href="/assets/uploads/2020/02/docker-compose-network-diagram-2-625.png"><img src="/assets/uploads/2020/02/docker-compose-network-diagram-2-625.png" alt="Network architecture of services orchestrated by docker-compose" /></a>&lt;figcaption&gt;Figure 1: Network architecture of services orchestrated by docker-compose&lt;/figcaption&gt;&lt;/figure&gt;</p>

  <p>Although this system worked pretty well, I have some issues with it.</p>

  <ol>
    <li>
      <p>All networks use a bridge network driver to provide network isolation of service groups. Therefore you have to create many networks, which in turn improves complexity.</p>
    </li>
    <li>
      <p>The network of <code class="language-plaintext highlighter-rouge">Reverse Proxy</code> has to be literally connected to all other bridges to have access to the web servers. <strong>However, this way the proxy container could access all exposed ports of all containers on any networks the proxy container is attached to.</strong> It provides a bigger attack surface.</p>
    </li>
    <li>
      <p>Docker makes these networking possible with lots of iptables rules (so as Podman) which are hard to overview and pollute the iptables rules you may already have.</p>
    </li>
  </ol>

  <h2 id="planning-the-conversion-of-docker-compose-services-to-pods">Planning the conversion of docker-compose services to pods</h2>

  <p>There is a very fundamental difference between Docker and Podman. <a href="https://developers.redhat.com/blog/2019/01/15/podman-managing-containers-pods/">Podman supports the concepts of pods</a> for instance. This is intentionally very similar to Kubernetes’ pods. Containers in a pod shares the same namespace, like network. So all containers in the same pod looks like sharing the same <code class="language-plaintext highlighter-rouge">localhost</code> network. And each pod has its own localhost.</p>

  <p>With Docker (Figure 1) there are 5 networks for 9 containers. With Podman by using pods there is only 1 network for 5 pods (Figure 2).</p>

  <figure class="wp-block-image size-large">
    <p><a href="/assets/uploads/2020/02/podman-network-diagram-2-625.png"><img src="/assets/uploads/2020/02/podman-network-diagram-2-625.png" alt="Network architecture of services orchestrated by podman" /></a>&lt;figcaption&gt;Figure 2: Network architecture of services orchestrated by Podman&lt;/figcaption&gt;&lt;/figure&gt;</p>

    <p>Pods provide another layer of isolation I really like. <strong>This way containers of any pods could only access ports published by other pods and not the containers themselves.</strong></p>

    <h2 id="challenges-with-podman">Challenges with Podman</h2>

    <p>Migrating to a new technology is not without compromises or challenges. Podman is around for a while and is rapidly evolving. Here are the challenges I had to handle.</p>

    <h3 id="assign-ip-addresses-to-pods-and-not-to-containers">Assign IP addresses to pods and not to containers</h3>

    <p>You can join a container to any networks. But a pod <a href="https://github.com/containers/libpod/issues/4718">can be only joined to the default network</a>. According to my understanding this will be changed later. This is the reason why I stick to the default network in my setup.</p>

    <blockquote>
      <p>“Most of the attributes that make up the Pod are actually assigned to the “infra” container.  Port bindings, cgroup-parent values, and kernel namespaces are all assigned to the “infra” container. “</p>
    </blockquote>

    <blockquote>
      <p>https://developers.redhat.com/blog/2019/01/15/podman-managing-containers-pods/</p>
    </blockquote>

    <p>By default pods will connect to network labeled <code class="language-plaintext highlighter-rouge">cni\_default\_network</code> in <code class="language-plaintext highlighter-rouge">libpod.conf</code>. If you join the pod’s containers to other networks, the pod will still have its IP assigned from the default network. However containers will have IPs assigned from the specified networks. As far as I know this symptom <a href="https://github.com/containers/libpod/issues/4908#issuecomment-577187947">looks like a bug</a>.</p>

    <h3 id="dns-name-resolution-between-containers-and-pods">DNS name resolution between containers and pods</h3>

    <p>By using the container plugin <a href="https://github.com/containers/dnsname">dnsname</a> you can get name resolution between containers on the same network. However at the moment you cannot have DNS between pods. <a href="https://github.com/containers/dnsname/issues/11">That feature is under development.</a></p>

    <p>While I am waiting for support of DNS on pod level, I worked around this limitation. I publish the exposed ports of pods to their gateway’s IP address 10.88.0.1 and not the IP address of their infra container itself. As long as the gateway’s IP address static this will work.</p>

    <h2 id="replacing-functionalities-of-docker-compose">Replacing functionalities of docker-compose</h2>

    <p>The YAML format of docker-compose uses an abstraction above ‘<code class="language-plaintext highlighter-rouge">docker run</code>’ command. However I realized that all the hard work docker-compose did to me was to create networks and assign container’s to them. And of course deploying services.</p>

    <h3 id="networking-rootfull-container-networking-cni">Networking: Rootfull container networking (CNI)</h3>

    <p>Luckily describing how a network should look like is not the role of Podman but <a href="https://github.com/containernetworking/plugins">CNI and its plugins</a>. You can see the layout of the default network in Figure 3.</p>

    <figure class="wp-block-image size-large">
      <p><a href="/assets/uploads/2020/02/podman-network-diagram-hld-625.png"><img src="/assets/uploads/2020/02/podman-network-diagram-hld-625.png" alt="topology of default network of podman " /></a>&lt;figcaption&gt;Figure 3. Low level network topology of Podman’s default network, called ‘podman’.&lt;/figcaption&gt;&lt;/figure&gt;</p>

      <p>The published ports are not visible from the outside network unless you set up routes externally. Or you can simply set the IP address of the host for serving published ports (<code class="language-plaintext highlighter-rouge">--publish 192.168.122.253:80:80</code>). Effectively it will be another DNAT rule. For my simple case it is enough.</p>

      <p>P.s. Do not forget to enable IP forwarding with sysctl to persist across reboots.</p>

      <p>P.s. 2: You may need to change the default firewall backend from iptables to firewalld in CNI configuration. So you will have a cleaner overview of your chains and rules.</p>

      <p><em>Rootless containers uses <a href="https://github.com/rootless-containers/slirp4netns">slirp4netns</a> instead of CNI. You can read more about the differences in this post <a href="http://Configuring container networking with Podman">configuring container networking with Podman</a>.</em></p>

      <h3 id="build-images-use-dockefile-to-build-an-image">Build images: use Dockefile to build an image</h3>

      <p>I really like that you do not have to learn another language to build an image. Use the same Dockerfile format you are already familiar with.</p>

      <p>Building an image is not the task of Podman but another tool called <a href="https://developers.redhat.com/blog/2019/02/21/podman-and-buildah-for-docker-users/">buildah</a>. Although you can even use <code class="language-plaintext highlighter-rouge">podman build</code>, it will actually use Buildah in the background. Assuming you have your Dockerfile in the current working directory, it will look like this. It can even publish the image to a Docker repository.</p>

      <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>buildah pull docker.io/opensuse/leap:15.1
buildah bud -t example/example-container:latest .
</code></pre></div>      </div>

      <h3 id="deployment-managing-container-life-cycles">Deployment: Managing container life-cycles</h3>

      <p>Docker-compose made it possible to deploy all services at once with <code class="language-plaintext highlighter-rouge">docker-compose up -d</code>. Achieving the same with Podman is possibly by using its <a href="https://developers.redhat.com/blog/2019/01/29/podman-kubernetes-yaml/">support for Kubernetes YAML</a> and some shell scripting.</p>

      <ol>
        <li>Set up the pods and containers with all the settings you need with plain <code class="language-plaintext highlighter-rouge">podman run</code> commands. Here is a shell script example for <a href="https://gitea.io">gitea</a>.</li>
      </ol>

      <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#!/bin/bash
podname="gitea"
version="1.9"
publish_ip="10.88.0.1"

podman pod rm -f ${podname} podman pod create --name ${podname} --hostname ${podname} -p ${publish_ip}:3000:3000

podman run -d --name ${podname}-svc --hostname ${podname}-svc --expose 3000 --pod ${podname} -e TZ="Europe/Budapest" \
 -v /srv/${podname}:/data \
 gitea/gitea:${version}
</code></pre></div>      </div>

      <ol>
        <li>Generate a Kubernetes compatible YAML file.</li>
      </ol>

      <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>podman generate kube -f gitea.yml gitea
</code></pre></div>      </div>

      <ol>
        <li>Replay it.</li>
      </ol>

      <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>podman pod rm -f gitea podman play kube gitea.yml
</code></pre></div>      </div>

      <p>I wrote a wrapper script called <a href="https://github.com/abalage/pods-compose">pods-compose</a> for imitating docker-compose start/stop/up/down but for pods to easy my life. There is a already post about <a href="/2020/03/31/managing-podman-pods-with-pods-compose/">managing Podman pods with pods compose.</a></p>

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

      <p>I did a lot of testing, so I managed to convert all docker-compose services to pods with Podman and with some shell scripting. I still have to figure out how to auto start of pods. There are <a href="https://www.redhat.com/sysadmin/podman-shareable-systemd-services">shareable systemd devices for containers</a>, but I want to test it for pods. See you next time.</p>
    </figure>
  </figure>
</figure>]]></content><author><name>Balázs Németh</name></author><category term="docker" /><category term="security" /><category term="linux" /><category term="network" /><category term="shell-script" /><summary type="html"><![CDATA[How to deploy pods with Podman when you only need a single-host system and not a complex Kubernetes. Convert your docker-compose services to pods with Podman.]]></summary></entry><entry><title type="html">Display OBD2 car metrics in Elasticsearch</title><link href="https://balagetech.com/2019/07/27/display-obd2-car-metrics-elasticsearch-elm327/" rel="alternate" type="text/html" title="Display OBD2 car metrics in Elasticsearch" /><published>2019-07-27T20:46:03+00:00</published><updated>2019-07-27T20:46:03+00:00</updated><id>https://balagetech.com/2019/07/27/display-obd2-car-metrics-elasticsearch-elm327</id><content type="html" xml:base="https://balagetech.com/2019/07/27/display-obd2-car-metrics-elasticsearch-elm327/"><![CDATA[<p>It is an experiment about displaying OBD2 car metrics in Elasticsearch. To see how fuel economy changes by changing your driving habits.
With the help of an ELM327 compatible OBD2 reader and a Android app <a href="https://play.google.com/store/apps/details?id=com.palmerperformance.DashCommand&amp;hl=en">Dashcommand</a> I could export OBD2 car metrics in Elasticsearch. The app also added GPS data. It was not as easy as it looked like at the beginning.</p>

<h2 id="what-is-obd2-car-metrics">What is OBD2 car metrics?</h2>

<p>OBD and OBD2 are standards for <a href="https://en.wikipedia.org/wiki/On-board_diagnostics">on-board diagnostics</a> of various vehicles like cars and trucks. Basically it is an interface for the car’s brain. With an OBD2 adapter you can query the status and metrics of various subsystems of a vehicle. You can find this port in almost any car manufactured in the last three decades.</p>

<p>This interface usually is not used by customers but by experienced car mechanics or technicians. There are many apps which can use an <a href="https://en.wikipedia.org/wiki/ELM327">ELM327</a> adapter to read data,  some even claim to clear Check Engine light too. However these cheap adapters are not comparable to professional devices which in are usually much more expensive and can do a lot more.</p>

<p>I have seen such professional devices which can even draw diagrams of metrics in real time. I though somehow the basics should be possible with Elasticsearch as well. Maybe not in real time. :)</p>

<h2 id="what-obd2-car-metrics-can-we-get">What OBD2 car metrics can we get?</h2>

<p>I drive a lot. Therefore one of my main motivation is to improve my fuel economy to simply save costs. I wanted to read the following metrics from my car.</p>

<ul>
  <li>
    <p>Speed</p>
  </li>
  <li>
    <p>Acceleration</p>
  </li>
  <li>
    <p>Fuel consumption (actual, average)</p>
  </li>
  <li>
    <p>Engine RPM, power and torque (the last two are calculated values)</p>
  </li>
  <li>
    <p>GPS latitude, longitude and altitude</p>
  </li>
</ul>

<p>Different apps were tested before but most of them either did not support exporting OBD2 car metrics nor could add GPS data to the metrics. I even put some effort to use <a href="https://play.google.com/store/apps/details?id=com.ovz.carscanner&amp;hl=en">Carscanner</a> and <a href="https://play.google.com/store/apps/details?id=org.y20k.trackbook&amp;hl=en">Trackbook GPS</a> together but although correlating data from two different apps <strong>was fun</strong>, but the results was not satisfying for at all. Creating an app from scratch was not an option as I wanted to focus my resources on visualization and understanding the data and not on developing an app.</p>

<p>After some trials I found two possible solutions. One of them was <a href="https://www.autopi.io/">AutoPi</a>, which looked very promising but it was too expensive (275 EUR) for the task. The other one was <a href="https://play.google.com/store/apps/details?id=com.palmerperformance.DashCommand&amp;hl=en">Dashcommand</a> which turned out absolutely worth the money (~ 7 EUR) for such a hobby project. It is capable to record much more data and metrics than I needed.</p>

<p>(I am really sorry AutoPi. I admit that I found you cooler than Dashcommand.)</p>

<h2 id="dashcommand">Dashcommand</h2>

<h3 id="basic-usage">Basic usage</h3>

<p>After you completed the first run wizard, specified your car’s details, you should go to Settings and check “Enable GPS”. On the main screen tap on DATA GRID and click on the computer icon to start recording metrics.</p>

<p>Once you stopped recording you should check LOG FILES on the main screen and export the logs as CSV files (spreadsheet file). Depending on the length of your track it will take some time to prepare the data and save it for you. Transfer it to your computer.</p>

<h3 id="processing-the-exported-data">Processing the exported data</h3>

<p>We have the CSV file but in its current format it is just a really huge mass of numeric data. Therefore I needed a tool to convert it into a format what Elasticsearch can ingest. I have developed a script in Perl using the <a href="https://metacpan.org/pod/Search::Elasticsearch">Search::Elasticsearch</a> library to send the records in the appropriate format to Elasticsearch.</p>

<p>Before you would use the script the index template mapping needs to be set in Elasticsearch. The procedure <a href="/visualizing-fail2ban-logs-in-kibana/#Create_index_template_for_Fail2ban_in_Elasticsearch">has been already described in my previous posts</a>. You can <a href="https://github.com/abalage/balagetech-dashcommand-parser-obd-elasticsearch/blob/master/elastic/index-mapping-dashcommand.txt">download the index template mapping</a> from GitHub. After the mapping is added you can <a href="https://github.com/abalage/balagetech-dashcommand-parser-obd-elasticsearch/blob/master/dashcommand-csv-parser.pl">use the script</a>.</p>

<p>The script requires a “-d” switch pointing to the CSV file you want to process and an “-e” switch pointing your Elasticsearch ingest node.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ perl dashcommand-csv-parser.pl -d DataLog.csv -e 1.2.3.4:9200 2&gt;/dev/null
</code></pre></div></div>

<p>In the example above I muted stderr as it gets polluted by the <a href="https://metacpan.org/pod/Search::Elasticsearch#trace_to">trace messages of Search::Elasticsearch library that I could not turn off</a>.</p>

<p>Please note, the resulted documents will not be consistent in terms of available key-value pairs. The reason is that not all metrics are available in every frame. This is expected. A sample document looks like this.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>{
  "_index": "dashcommand-2019-06-19",
  "_type": "_doc",
  "_id": "pQfBk2sB4oJcycVygM3v",
  "_version": 1,
  "_score": null,
  "_source": {
    "calc.fuel_flow_avg l/h": "4.306",
    "calc.acceleration_g g": "-0.000",
    "@timestamp": "2019-06-19T07:19:17",
    "sae.maf g/s": "2.06",
    "calc.fc.ifc_avg l/100km": "5.9",
    "sae.vss km/h": "0",
    "calc.map kpa": "31.6",
    "frame number": "8134",
    "calc.fuel_flow l/h": "0.704",
    "calc.engine_power hp": "2",
    "calc.distance km": "242.4",
    "calc.acceleration m/s²": "-0.000",
    "sae.iat °c": "38",
    "calc.engine_torque n·m | kg-f·m": "25",
    "sae.rpm rpm": "716",
    "calc.boost_pressure kpa | bar | kg-f/cm²": "-0.674",
    "sae.sparkadv °": "3.0"
  },
  "fields": {
    "@timestamp": [
      "2019-06-19T07:19:17.000Z"
    ]
  }
}
</code></pre></div></div>

<h3 id="further-readings-about-obd-data-and-metrics">Further readings about OBD data and metrics</h3>

<p>If you are interested in about what these metrics mean. I highly suggest to check the following links. I found them really helpful during my work.</p>

<ul>
  <li>
    <p><a href="http://lcsi.umh.es/docs/pfcs/PFC_TFG_Bocanegra_Fernando.pdf">EXTRACTION AND ANALYSIS OF CAR DRIVING DATA VIA OBD-II</a> by Fernando Bocanegra Gallardo - (Chapter 5. Analysis)</p>
  </li>
  <li>
    <p><a href="https://www3.epa.gov/ttn/chief/conference/ei20/session8/aalessandrini_pres.pdf">Consumption calculation of vehicles using OBD data</a> by Adriano Alessandrini, Francesco Filippi, Fernando Ortenzi</p>
  </li>
  <li>
    <p><a href="https://www.palmerperformance.com/download/CALC_PID_Reference.pdf">CALC_PID_Reference.pdf</a> - by Palmer Performance, vendor of Dashcommand</p>
  </li>
  <li>
    <p><a href="https://www.palmerperformance.com/download/Vehicle_Settings.pdf">Vehicle_Settings.pdf</a> - by Palmer Performance, vendor of Dashcommand</p>
  </li>
</ul>

<h2 id="elasticsearch-and-kibana">Elasticsearch and Kibana</h2>

<p>All these stuff means nothing without shiny visualizations right?</p>

<p><a href="/assets/uploads/2019/07/obd-dashboard-elasticsearch-1250.png"><img src="/assets/uploads/2019/07/obd-dashboard-elasticsearch-625.png" alt="Dashboard of OBD2 car metrics in Elasticsearch" /></a>Dashboard showing all the metrics I mentioned at the beginning.</p>

<h3 id="visualizing-gps-altitude-in-kibana">Visualizing GPS altitude in Kibana</h3>

<p>Here is a tricky one. In my previous posts like in <a href="/visualizing-nginx-access-logs-kibana/#Creating_a_Coordinate_Map_visualization_for_GeoIP_data_of_HTTP_clients">NGINX visualization</a>, or <a href="/visualizing-fail2ban-logs-in-kibana/#Visualizing_Fail2ban_logs_in_Kibana">Fail2ban visualization</a> I have shown that in Kibana you can easily visualize locations by the latitude and longitude data. But what about altitude?</p>

<p>Change the aggregation type from the default <strong>Count</strong> to <strong>Max</strong> and the field to <strong>aux.gps.altitude</strong>. It will effectively show the maximum value of the altitude. The value actually reflects the geological altitude on the map. It is sad that the map visualization is only 2D.</p>

<p><a href="/assets/uploads/2019/07/obd-altitude-elasticsearch-1250.png"><img src="/assets/uploads/2019/07/obd-altitude-elasticsearch-625.png" alt="OBD Altitude data in Geo Map" /></a>Tip: Do the same trick with line charts with chart type set to area. It will look like a cross-section of a map.</p>

<h3 id="where-is-north">Where is North?</h3>

<p>The GPS records contain the actual GPS course too. By using the Gauge visualization and a narrow enough time interval you can actually see your direction. You have to set up at least 4 ranges according to a 360 degrees circle. It is a bit quirky I know. If you set up more ranges, then it will look like as a compass.<a href="/assets/uploads/2019/07/obd-north-elasticsearch-1250.png"><img src="/assets/uploads/2019/07/obd-north-elasticsearch-625.png" alt="GPS Course in Gauge Elasticsearch" /></a></p>

<h3 id="how-my-fuel-consumption-looked-like">How my fuel consumption looked like?</h3>

<p>As we have almost all OBD2 car metrics in Elasticsearch, we can put both average and instantaneous fuel consumption on a <a href="/simplified-logging-docker-elasticsearch-syslog-ng/#Creating_a_stacked_Vertical_Bar_visualization">stacked bar chart</a>.</p>

<p><a href="/assets/uploads/2019/07/obd-fuel-consumption-elasticsearch-1250.png"><img src="/assets/uploads/2019/07/obd-fuel-consumption-elasticsearch-625.png" alt="Fuel consumption Elasticsearch" /></a>Looks like I had a moment of full throttle at the end of my trip. :)</p>

<h2 id="verdict">Verdict</h2>

<p>Should you like to see your car’s data in Elasticsearch, then download all visualizations and dashboards from <a href="https://github.com/abalage/balagetech-dashcommand-parser-obd-elasticsearch">the projects GitHub repository</a>. I only tested the script under Linux. It may or may not work under Windows. It is time to give your car a ride. :)</p>]]></content><author><name>Balázs Németh</name></author><category term="tutorials" /><category term="android" /><category term="elasticsearch" /><category term="kibana" /><category term="obd" /><category term="perl" /><summary type="html"><![CDATA[It is an experiment about displaying OBD2 car metrics in Elasticsearch. To see how fuel economy changes by changing your driving habits. With the help of an ELM327 compatible OBD2 reader and a Android app Dashcommand I could export OBD2 car metrics in Elasticsearch. The app also added GPS data. It was not as easy as it looked like at the beginning.]]></summary></entry><entry><title type="html">Which Android app phones home to China?</title><link href="https://balagetech.com/2019/04/27/android-app-phones-home-china/" rel="alternate" type="text/html" title="Which Android app phones home to China?" /><published>2019-04-27T13:47:35+00:00</published><updated>2019-04-27T13:47:35+00:00</updated><id>https://balagetech.com/2019/04/27/android-app-phones-home-china</id><content type="html" xml:base="https://balagetech.com/2019/04/27/android-app-phones-home-china/"><![CDATA[<p>In my previous blog post I created a system to <a href="/2019/03/20/monitor-network-traffic-openwrt-syslog-ng/">monitor my network traffic</a>. This system is capable to visualize connections <a href="/2019/02/09/visualizing-nginx-access-logs-kibana/">even in geographic manner</a>. Checking the data I found two network devices who phones home to servers located in China. What can I find out about those connections. What are they? Do they pose any security threat to me?</p>

<p>My sole purpose was to experiment and learn new things. Please mind that I could pick any other countries the same way as I chose China. Although I have security concerns, <strong>I want to learn and not to make statements over any countries or vendors</strong>.</p>

<h2 id="finding-out-who-phones-home-to-china">Finding out who phones home to China</h2>

<p>The starting point for my experiments is getting network details from my <a href="/2019/03/20/monitor-network-traffic-openwrt-syslog-ng/">network monitoring system</a> to get some insights about traffic.</p>

<ul>
  <li>
    <p>I have a list of IP addresses of servers which are located in China. So as the number of occasions and size of transferred data of the connections.</p>
  </li>
  <li>
    <p>All traffic took place over plain HTTP which are not encrypted. Even the one which addressed port TCP 443.</p>
  </li>
  <li>
    <p>Traffic were initiated by two different Android phones in our household. (I also made some traffic to China from another host during troubleshooting, therefore I excluded that host from the report.)</p>
  </li>
</ul>

<p><a href="/assets/uploads/2019/04/china-details-data-table-1250.png"><img src="/assets/uploads/2019/04/china-details-data-table-625.png" alt="List of devices who phones home to China IP addresses" /></a></p>

<p>The biggest pain point here is for performance and capacity reasons my setup did not collect network packets themselves but only metadata.
At this point I was only aware of the connections but did not have visibility about their actual content.</p>

<h2 id="creating-packet-captures-from-network-traffic">Creating packet captures from network traffic</h2>

<p>Packet captures should take place <a href="https://balagetech.com/creating-a-central-syslog-server/#Adding_OpenWRT_logs_via_network_sources">on the router device</a>. I was expecting if there is something what phones home to China, it may try again. Therefore I executed a tcpdump command to save any future traffic matching any IP address from the list I specified.
For your reference, I used this command to capture packets.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>tcpdump -peni any -s 0 -w /path/to/storage/capture.pcap tcp \
(host 203.205.151.2 or host 120.92.96.13 or host 123.125.102.48 \ 
or host 183.84.5.221 or host 42.62.94.2 or host 140.205.61.53 \ 
or host 42.120.158.121 or host 106.11.186.5 or host 106.11.248.98)
</code></pre></div></div>

<p>After more than a week I had enough traffic captured to analyze it with Wireshark. Albeit I noticed that not all IP address from the list had packets in the pcap.</p>

<p>If you are interested in, I mounted a remote server’s storage via sshfs on OpenWRT to circumvent the small storage the router has.</p>

<h2 id="analyzing-packet-captures-with-wireshark">Analyzing packet captures with Wireshark</h2>

<p>As it turned out all connection were plain HTTP. As a first step I made <a href="https://www.wireshark.org/">Wireshark</a> to save all HTTP objects from the capture file. Simply following <strong>“File → Export objects → HTTP…“</strong> already reveals a lot of details.</p>

<p><a href="/assets/uploads/2019/04/wireshark-saved-http-objects-1250.png"><img src="/assets/uploads/2019/04/wireshark-saved-http-objects-625.png" alt="Wireshark saved HTTP objects" /></a>HTTP requests and responses contain a lot of things, like URI of the HTTP request, the server name. The parameters of GET and PUT requests can also reveal the actual traffic. While User Agent can give hints about the application which initiated the connection. And so on.</p>

<p>Let’s see what information we can get from the HTTP headers and responses.</p>

<p>It looks like whoever is trying to phoning home to China is probably addressing QQ or Xiaomi servers.</p>

<h3 id="case-1-samsung-galaxy-a5-2016">Case 1: Samsung Galaxy A5 2016</h3>

<p>This phone is a Samsung Galaxy phone and it has a private IP address of 172.18.0.102.
This devices constantly made requests to destination 203.205.151.21.</p>

<h4 id="ip-20320515121">IP: 203.205.151.21</h4>

<p>Here are the HTTP request and response headers.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>GET /qqconnectopen/openapi/policy_conf?status_os=7.0&amp;status_version=24&amp;status_machine=SM-A510F&amp;sdkp=a&amp;sdkv=3.3.0.lite&amp;appid=1103177325 HTTP/1.1
Accept-Encoding: gzip
Host: cgi.connect.qq.com
Connection: Keep-Alive
User-Agent: AndroidSDK_24_a5xelte_7.0 
</code></pre></div></div>

<ul>
  <li>
    <p>The web server host is “cgi.connect.qq.com”. The domain qq.com belongs to <a href="https://en.wikipedia.org/wiki/Tencent_QQ">Tencent QQ</a> which is a Chinese instant messaging app vendor.</p>
  </li>
  <li>
    <p>The web server software is “tws”</p>
  </li>
  <li>
    <p>The GET request URI sends OS version information and phone brand and type to the requested site. The string qqconnectopen I think is actually referring to <a href="http://open.qq.com/eng/">Tencent’s Open Platform</a>.</p>
  </li>
  <li>
    <p>By the way from the User-Agent, they can also decode the brand and type of the phone, so as the major version of Android it runs.</p>
  </li>
</ul>

<p>Wireshark decoded the gzipped response as well. It is actually a JSON response. I only did a pretty print for better readability.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>HTTP/1.1 200 OK
Date: Tue, 02 Apr 2019 05:27:13 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Server: tws
Vary: Accept-Encoding
Content-Encoding: gzip

{
   "Common_SSO_QZoneSchema" : "mqzone",
   "Common_DownloadReportMaxcount" : 3,
   "Common_tips_dialog_interval" : 2000,
   "Common_DownloadReportTimeinterval" : 36000,
   "Common_CGIReportTimeinterval" : 1200,
   "Agent_ReportTimeInterval" : 5000,
   "Common_WebReportFrequency" : 1,
   "Common_QQ_VERSION" : 10000,
   "Common_Release_Control" : "-1",
   "Common_SSO_QzoneVersion" : "3.6.8",
   "Common_root_autoinstall_flag" : 1,
   "Common_ApkUpdateConfig" : 1,
   "Common_frequency" : 1,
   "Common_Appstore_FullUpdateOnly" : 0,
   "Common_WNS_Theme_Switch" : 0,
   "Common_Max_Count" : -1,
   "Common_ta_enable" : 1,
   "Common_Dialog_Only_Once_Flag" : false,
   "Common_BusinessReportMaxcount" : 1,
   "Common_WNS_Channel_Switch" : 1,
   "Common_Show_Dialog_Flag" : true,
   "Common_CGIReportFrequencySuccess" : 10,
   "Common_DownloadReportFrequency" : 1,
   "Common_PushReportFrequency" : 1,
   "C_Full_Report" : true,
   "Agent_ReportBatchCount" : 5,
   "Common_Detail_Page" : true,
   "Common_CGIReportMaxcount" : 5,
   "Common_myapp_download_url" : "http://a.app.qq.com/o/myapp-down?g_f=991310",
   "C_LoginH5" : true,
   "Common_114DNS_Resolve_All" : false,
   "Common_HttpRetryCount" : 3,
   "Common_CGIReportFrequencyFailed" : 100,
   "Common_MyAppDownload_Flag" : true,
   "Common_114DNS_Resolve_Timeout" : 10,
   "C_LoginWeb" : false,
   "Common_BusinessReportTimeinterval" : 1,
   "Common_HttpConnectionTimeout" : 15000,
   "Common_BusinessReportFrequency" : 100,
   "Common_CGIReportFrequency" : 100,
   "Common_yyb_wifi_download_Switch" : true,
   "Common_SocketConnectionTimeout" : 30000,
   "Common_require_root_interval" : 86400000,
   "ret" : 0,
   "Common_114DNS_CGI_To_Resolve" : "",
   "Common_QQ_Patch_Switch" : true
}
</code></pre></div></div>

<ul>
  <li></li>
  <li>
    <p><a href="https://en.wikipedia.org/wiki/Qzone">QZone</a> is a Chinese social network. I do not have anything like that installed.</p>
  </li>
  <li>The Common_myapp_download_url points to an APK you can actually download. The APK names itself as com.tencent.android.qqdownloader (QQDownloader) which is the <a href="https://blog.trustlook.com/2015/11/12/analysis-of-repackaged-applications-from-over-one-thousand-qqdownloaders-in-global-android-marketplaces/">Chinese counter part of Google Play</a>. If you want to see more details about the APK then have a look at the <a href="https://www.virustotal.com/#/file/ef0aef45106efce018c1ff76bf77e8fddb6ba96514e94b37f526a51d998f574a/details">analysis done by VirusTotal</a>.
The most interesting parts are the Android permissions it requires. It is simply a ‘superuser’ app.</li>
</ul>

<p>Recently because this phone had issues I decided to do a factory reset and root it. Since then there were no new connection which tried to phone home to China. <span style="text-decoration: underline;">Unfortunately I am able to further audit this kind of traffic.</span></p>

<h3 id="case-2-samsung-galaxy-j5-2016">Case 2: Samsung Galaxy J5 2016</h3>

<p>This is phone is also a Samsung Galaxy phone and it has a private IP address of 172.18.0.220. This devices constantly makes HTTP(S) requests to the following destinations:</p>

<ul>
  <li>
    <p>42.62.94.2</p>
  </li>
  <li>
    <p>120.92.96.13</p>
  </li>
  <li>
    <p>123.125.102.48</p>
  </li>
  <li>
    <p>183.84.5.221</p>
  </li>
</ul>

<h4 id="ip-4262942">IP: 42.62.94.2</h4>

<p>The clients addressed TCP port 443. Although the TCP handshake was okay no HTTPS connections were established. Checking the PSH, ACK flags I can see the following TCP payload in ASCII dump. I do not think they run a HTTPS service on that port.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>.......r.......T...
xiaomi.com*.CONNH..j.	SM-J510FN..J510FNXXS2AQI4".GkdbaFv1C3GJT-F3(%2.wifi:.42.62.94.2:443B.hu_HUJ...P..).@
</code></pre></div></div>

<p>Visible things are:</p>

<ul>
  <li>
    <p>xiaomi.com</p>
  </li>
  <li>
    <p>identifiers of the phone device, exact firmware and its locale</p>
  </li>
</ul>

<h4 id="ip-120929613-12312510248-and-183845221">IP: 120.92.96.13, 123.125.102.48 and 183.84.5.221</h4>

<p>There were daily logins to these IP addresses on plain HTTP. Let’s check the HTTP requests and responses. They are the same for all IPs.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>GET /gslb/?ver=4.0&amp;type=wifi&amp;uuid=0&amp;list=app.chat.xiaomi.net%2Cresolver.msg.xiaomi.net&amp;sdkver=37&amp;osver=23&amp;os=SM-J510FN%3AJ510FNXXS2AQI4&amp;mi=0&amp;key=6d8fafdcbfacf6c3eec939d746ac3370 HTTP/1.1
User-Agent: Dalvik/2.1.0 (Linux; U; Android 6.0.1; SM-J510FN Build/MMB29M)
Host: resolver.msg.xiaomi.net
Connection: Keep-Alive
Accept-Encoding: gzip
</code></pre></div></div>

<p>The response is again a JSON file. I only did a pretty print here for better readability.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>HTTP/1.1 200 OK
Server: Tengine/2.2.2
Date: Tue, 02 Apr 2019 19:11:34 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 744
Connection: keep-alive

{
   "R" : {
      "stat-domain" : "s.mi1.cc",
      "wifi" : {
         "app.chat.xiaomi.net" : [
            "47.74.170.155:5222",
            "47.74.170.157:5222",
            "47.74.170.158:5222",
            "47.74.170.157:80",
            "47.74.170.158:80",
            "47.74.170.155:80",
            "47.74.170.155:443",
            "47.74.170.157:443",
            "47.74.170.158:443"
         ],
         "resolver.msg.xiaomi.net" : [
            "161.117.97.14:80"
         ]
      },
      "wap" : {
         "resolver.msg.xiaomi.net" : [
            "161.117.97.14:80"
         ],
         "app.chat.xiaomi.net" : [
            "47.74.170.155:5222",
            "47.74.170.157:5222",
            "47.74.170.158:5222",
            "47.74.170.157:80",
            "47.74.170.158:80",
            "47.74.170.155:80",
            "47.74.170.155:443",
            "47.74.170.157:443",
            "47.74.170.158:443"
         ]
      },
      "city" : "",
      "ttl" : 3600,
      "ip" : "80.99.22.19",
      "X-Forwarded-Ip" : "80.99.22.19",
      "tid" : -1,
      "stat-percent" : 0.05,
      "force-use" : "false",
      "isp" : "",
      "country" : "",
      "extra-for-pa" : "debug info",
      "province" : ""
   },
   "S" : "Ok"
}
</code></pre></div></div>

<p>For me this looks like a configuration update, but also sends data to the servers.
The following data are collected from our phone device:</p>

<ul>
  <li>
    <p>Phone brand and type</p>
  </li>
  <li>
    <p>Android OS version and exact firmware version</p>
  </li>
  <li>
    <p>My IP address (and therefore my rough location)</p>
  </li>
</ul>

<p>There is one more thing. You can see they use an <a href="https://github.com/alibaba/tengine">Tengine</a> as webserver which is a fork of NGINX. That is developed by Taobao which is owned by Alibaba. The domain mi1.cc is actually redirects to miliao.com which is a social network site of Xiaomi. As that phone also has MI Fit installed the traffic might been caused by that app. Although there is no clear evidence.</p>

<h2 id="conclusions">Conclusions</h2>

<p>Simply matching a network traffic to a process on and Android phone is almost impossible without host level information from the phone itself.</p>

<p>Looking through the installed apps on both phones I could only find <a href="https://play.google.com/store/apps/details?id=com.xiaomi.hm.health&amp;hl=hu">MI Fit</a> app which has explicit connections to a Chinese company. The App MI Fit is produced by <a href="https://www.huami.com/investor">Huami</a> (subsidiary of Xiaomi) who clearly states they own a large bio-metric and activity database and they collect bio-metric data from more than 50 Million users.</p>

<p>I admit I use Xiaomi and Huami products, so as I <a href="http://cdn.awsbj0.fds.api.mi-img.com/mifit/1480831742.html">made my consent</a> when I installed MI Fit. <span style="text-decoration: underline;">My experiment proves that statistical personal data is actually sent to China, unencrypted. </span>The fact that all of these connections were made over plain HTTP does not reassure me about <a href="https://en.wikipedia.org/wiki/History_of_Xiaomi#Privacy_concerns">their approach to security</a>.<span style="text-decoration: underline;"> </span></p>

<p>However keep in mind that my geographic approach is very prone to dismissing traffic to other countries. The fact that in an about two week long packet capture I could not find much data sent to China does not mean <a href="https://www.iot-tests.org/2018/08/in-the-security-check-xiaomi-mi-band-2/">there were no data sent to other countries</a>.</p>

<p>I also note that I could not find any explicit connection between QQConnect and Xiaomi. If do you have any information about it then let me know in the comments.</p>

<p>You can see that neither the brand nor the type of the mobile phones were really playing any role in this case. At least I am not aware of them.</p>

<p>For me it was an experiment with geographic network data. Although GeoIP provided useful information, I think in the world of CDNs and VPNs it cannot be a single point of truth. It just provides one aspect.</p>

<h3 id="alternatives-to-improve-your-privacy">Alternatives to improve your privacy</h3>

<p>If you care about privacy and you do not want to give your consent to companies use your bio-metric data then you will have other options.
In case your wearable device is supported, then have a look at <a href="https://gadgetbridge.org/">Gadgetbridge</a>. It is an open source alternative to MI Fit and it does not require you to have MI Fit installed. But bear in mind that is still in development phase.</p>

<p>If you do not want to replace MI Fit, then you can limit its network usage with <a href="https://www.netguard.me/">NetGuard</a>. Although this have the downside of not being able to update the firmware of the device or pairing a new one.</p>

<p>If you liked this post then please share it. Should you have any comments then please leave a reply below. I would really appreciate it.</p>

<p>Thank you.</p>]]></content><author><name>Balázs Németh</name></author><category term="security" /><category term="android" /><category term="china" /><category term="geoip" /><category term="packet-capture" /><summary type="html"><![CDATA[In my previous blog post I created a system to monitor my network traffic. This system is capable to visualize connections even in geographic manner. Checking the data I found two network devices who phones home to servers located in China. What can I find out about those connections. What are they? Do they pose any security threat to me?]]></summary></entry><entry><title type="html">Monitor home network traffic with OpenWRT and Syslog-ng and Elasticsearch Security</title><link href="https://balagetech.com/2019/03/20/monitor-network-traffic-openwrt-syslog-ng/" rel="alternate" type="text/html" title="Monitor home network traffic with OpenWRT and Syslog-ng and Elasticsearch Security" /><published>2019-03-20T12:01:53+00:00</published><updated>2019-03-20T12:01:53+00:00</updated><id>https://balagetech.com/2019/03/20/monitor-network-traffic-openwrt-syslog-ng</id><content type="html" xml:base="https://balagetech.com/2019/03/20/monitor-network-traffic-openwrt-syslog-ng/"><![CDATA[<p>Monitor home network traffic with OpenWRT and Syslog-ng with Elasticsearch Security. I wanted to see what happens on my home network. Is there something going on I should be aware of? Is there any device which creates suspicious connections like phoning home? I will use OpenWRT and syslog-ng to get the answers and Elasticsearch Security to get the analytics.<a href="/assets/uploads/2019/03/kibana-dashboard-outgoing-connections-2-1250.png"><img src="/assets/uploads/2019/03/kibana-dashboard-outgoing-connections-2-625.png" alt="Kibana dashboard showing data from OpenWRT traffic syslogs" /></a></p>

<h2 id="important-updates-12022023"><strong>Important updates: 12/02/2023</strong></h2>

<p>This post seems like getting some of attention from various people recently and I am very happy about it. I understand the need of reproducible configurations both for Syslog-NG and Elasticsearch, I would expect it too. I tried to address most of the problems mentioned in the comment section. The following changes occurred.</p>

<ol>
  <li>
    <p>syslog-ng’s configuration has been refactored and updated to match up version 4.5.0, also many hard wired settings are now populated via environment variables.</p>
  </li>
  <li>
    <p>A Dockerfile is provided to help people who requires container images. This image is only meant for transforming <span style="text-decoration: underline;">fail2ban</span>, <span style="text-decoration: underline;">dnsmasq</span>, <span style="text-decoration: underline;">unbound</span> and <span style="text-decoration: underline;">ulogd2</span> logs to Elasticsearch. <strong>Although you can send any kind of logs to TCP 6514 (IETF syslog) or TCP 514 (BSD syslog) of the container, do not expect them to be properly indexed by Elasticsearch.</strong></p>
  </li>
  <li>
    <p><strong><span style="color: #ff0000;">Be aware.</span></strong> The Dockerfile initializes a copy of <strong>GeoLite2-City.mmdb</strong> from a 3rd party site. It is only for testing, implement your own <a href="https://dev.maxmind.com/geoip/updating-databases">method to fetch maps complying to the license requirements</a>.</p>
  </li>
  <li>
    <p>The legacy index template “network” has been converted to composable template. Tested it with Elasticsearch 8.7.1</p>
  </li>
  <li>
    <p>Elasticsearch was installed by using this <a href="https://github.com/elkninja/elastic-stack-docker-part-one/tree/main">elkninja/elastic-stack-docker-part-one/docker-compose.yaml</a>.</p>
  </li>
</ol>

<p>Regarding Elasticsearch I have changed my mind. It is simply an overkill for most people who monitors home network traffic with OpenWRT and Syslog-ng. Even I myself have abandoned it 2 years ago. Although I updated Elasticsearch configurations but they are not thoroughly tested and I am not even planning to test it in the future. I have plans to look for another more lightweight solutions for visualizations. And maybe run it next to <a href="/2023/06/15/running-home-assistant-on-kubernetes/">Home Assistant on Kubernetes</a>. :)</p>

<h2 id="about-monitoring-home-network-traffic-with-openwrt-and-syslog-ng">About monitoring home network traffic with OpenWRT and Syslog-ng</h2>

<p>SOHO routers are usually not really resourceful, neither is mine. Therefore I needed a solution using as little resource as possible but still capable to answers that questions. My solution uses connection tracking data from an OpenWRT router. Offload the information from OpenWRT to a <a href="/2019/01/14/creating-a-central-syslog-server/">central syslog server</a>. Enrich it with GeoIP and session length metadata by using syslog-ng. Then analyze the logs with Elasticsearch. Recently it has been also enchanced with DNS information thanks to either dnsmasq or unbound DNS servers.</p>

<p>The first part of this blog series answers where the packets come and go and some metrics. What are inside the packets is up to another posts.</p>

<h2 id="logging-connection-tracking-data-with-openwrt-and-syslog-ng">Logging connection tracking data with OpenWRT and syslog-ng</h2>

<p>My original idea was <a href="https://en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_establishment">to log the SYN and ACK,FIN packets</a> with Iptables <a href="https://openwrt.org/docs/guide-user/firewall/netfilter_iptables/iptables_log_targets">on the FORWARD chain</a> and correlate them. However it did not work as I planned. Although the most important data are included in syslog messages like network source, destination, port numbers. However the logs cannot be easily correlated to each other to get session data because there is no common identifier in iptables logs which would be unique to any given connection. (Stream ID would be but it is encoded in TCP options.) Logging all packets would simply kill the performance so it is not worth it. I needed an alternative solution.</p>

<p>Founding an essay about <a href="https://www.kernel.org/doc/ols/2005/ols2005v2-pages-273-278.pdf">Flow-based network accounting in Linux</a> did turn the tide. I realized that ‘nf_conntrack’ in Linux kernel (netfilter) actually keeps track of every connections throughout their lifetime (even UDP which is stateless). I only needed a tool to get that data off the OpenWRT router possibly to syslog-ng. The essay mentioned many tools but <a href="https://www.netfilter.org/projects/ulogd/index.html">ulogd</a> looked the most promising.</p>

<p>Ulogd is capable to log connection tracking data to local syslog. The following example shows a NEW and a DESTROY event of a specific connection logged by ulogd.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Mar 13 15:03:57 openwrt ulogd[21765]: [NEW] ORIG: SRC=172.18.0.227 DST=1.2.3.4 PROTO=TCP SPT=57534 DPT=443 PKTS=0 BYTES=0 , REPLY: SRC=1.2.3.4 DST=5.6.7.8 PROTO=TCP SPT=443 DPT=57534 PKTS=0 BYTES=0
Mar 13 15:09:00 openwrt ulogd[21765]: [DESTROY] ORIG: SRC=172.18.0.227 DST=1.2.3.4 PROTO=TCP SPT=57534 DPT=443 PKTS=9 BYTES=3371 , REPLY: SRC=1.2.3.4 DST=5.6.7.8 PROTO=TCP SPT=443 DPT=57534 PKTS=8 BYTES=1301
</code></pre></div></div>

<p><em>Note: 1.2.3.4 represents a website, while 5.6.7.8 represents the public IP of my home network.</em></p>

<h3 id="configuring-ulogd2-on-openwrt-to-send-conntrack-events-to-syslog-ng">Configuring ulogd2 on OpenWRT to send conntrack events to syslog-ng</h3>

<p>My OpenWRT systems already send their syslog to a remote <a href="/creating-a-central-syslog-server/#Adding_OpenWRT_logs_via_network_sources">central syslog server</a>. OpenWRT uses logread to send syslogs remotely. The remote server runs on syslog-ng. Therefore I only have to configure ulogd to send the connection tracking events to local syslog instead of a file.</p>

<p>Fortunately ulogd can send the events to many destinations. I found a post about <a href="https://home.regit.org/2014/02/logging-connection-tracking-event-with-ulogd/">logging connection tracking events with ulogd</a> and it helped me to configure the service properly.<br />
On the following link you can find the <a href="https://github.com/abalage/balagetech-openwrt-syslog-ng-elasticsearch/blob/master/openwrt/etc/ulogd.conf">complete configuration of ulogd</a> I created for OpenWRT 18.06 (works with 19.07 too). Nevertheless I describe the details below as well.</p>

<ol>
  <li>First you have to install ulogd and some of its modules. You can do this either in LuCI or in the command line.</li>
</ol>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>root@openwrt:~# opkg update \
&amp;&amp; opkg install ulogd ulogd-mod-nfct ulogd-mod-syslog ulogd-mod-extra
</code></pre></div></div>

<ol>
  <li>
    <p>The configuration of ulogd uses an <a href="https://en.wikipedia.org/wiki/INI_file">INI style syntax</a>. Two sections will be important for us, [global] and [ct1].<br />
In [global] section after the list of plugins there will be presets of stacks. Stacks are a list of plugins and they work like commands piped together. There are input plugins, filter plugins and output plugins.</p>
  </li>
  <li>
    <p>Look for the comment below. We are going to adjust the stack belonging to that comment like this.</p>
  </li>
</ol>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># this is a stack for flow-based logging via LOGEMU
stack=ct1:NFCT,ip2str1:IP2STR,print1:PRINTFLOW,sys1:SYSLOG
</code></pre></div></div>

<ol>
  <li>Look for the section called [ct1]. We are adding a new configuration element called <em>hash_enable</em>. Disabling hashes makes ulogd to log both NEW and DESTROY events separately. Otherwise it would only log DESTROY events. Although DESTROY contains everything we need the NEW events as well because of their timestamps, because we will make use of them for building session metadata.</li>
</ol>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[ct1]
hash_enable=0
</code></pre></div></div>

<ol>
  <li>You can do a manual check of the configuration by starting ulogd manually.</li>
</ol>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>root@openwrt:~# ulogd -v
Mon Mar 11 15:42:51 2019 &lt;5&gt; ulogd.c:843 building new pluginstance stack: 'ct1:NFCT,ip2str1:IP2STR,print1:PRINTFLOW,sys1:SYSLOG'
Mon Mar 11 15:42:51 2019 &lt;5&gt; ulogd_inpflow_NFCT.c:1399 NFCT plugin working in event mode
</code></pre></div></div>

<ol>
  <li>The last step is to enable the service and start it.</li>
</ol>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>root@openwrt:~# /etc/init.d/ulogd enable
root@openwrt:~# /etc/init.d/ulogd start
</code></pre></div></div>

<p>That is all you have to do to make OpenWRT send its connection tracking events to syslog-ng.</p>

<p><strong>Update:</strong> Note for general Linux users. I found that netfilter accounting is usually disabled in kernels, especially on OpenSUSE Leap. This will result that PKTS and BYTES will always be 0. To overcome this one must enable accounting by executing the following command.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># runtime only
root@opensuse:~# echo "1"&gt; /proc/sys/net/netfilter/nf_conntrack_acct
# make it permanent across system reboots
root@opensuse:~# echo 'net.netfilter.nf_conntrack_acct=1' &gt; /etc/sysctl.d/100-custom.conf
</code></pre></div></div>

<p>Thanks to <a href="https://home.regit.org/2014/02/logging-connection-tracking-event-with-ulogd/">Eric Leblond’s great blog article</a> for mentioning it.</p>

<h2 id="processing-ulogd-log-messages-from-openwrt-with-syslog-ng">Processing ulogd log messages from OpenWRT with syslog-ng</h2>

<p>My goal is to parse and enrich ulogd messages with metadata like duration and GeoIP. Syslog-ng provides many parsers to use out of the box. You can see a short overview about the parsers I use in this case.</p>

<table>
  <thead>
    <tr>
      <th><strong>Metadata we add to logs</strong></th>
      <th><strong>Syslog-ng parsers providing the metadata</strong></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>separate upstream and downstream metrics</td>
      <td><a href="https://www.syslog-ng.com/technical-documents/doc/doc1094716">csv-parser()</a></td>
    </tr>
    <tr>
      <td>parsing key-value pairs from all streams</td>
      <td><a href="https://www.syslog-ng.com/technical-documents/doc/doc1094718">kv-parser()</a></td>
    </tr>
    <tr>
      <td>creating session start, session end and length</td>
      <td><a href="https://www.syslog-ng.com/technical-documents/doc/syslog-ng-open-source-edition/3.19/administration-guide/79#TOPIC-1094769">grouping-by()</a></td>
    </tr>
    <tr>
      <td>GeoIP metadata</td>
      <td><a href="https://www.syslog-ng.com/technical-documents/doc/syslog-ng-open-source-edition/3.19/administration-guide/81#TOPIC-1094778">geoip2()</a></td>
    </tr>
    <tr>
      <td>Enrich DNS data from PublicSuffixList</td>
      <td><a href="https://www.syslog-ng.com/technical-documents/doc/doc1094731">python()</a></td>
    </tr>
  </tbody>
</table>

<p>Some parsers can be chained together in a single <strong>parser{}</strong> block. They behave like commands piped together in a Linux shell. One parser’s output will feed the input of the next parser. Thus their order is important.</p>

<p>As the configuration is rather long and complex I uploaded <a href="https://github.com/abalage/balagetech-openwrt-syslog-ng-elasticsearch/blob/master/syslog-ng/etc/syslog-ng/conf.d/network-ulogd2.conf">the complete syslog-ng configuration file to GitHub</a>.</p>

<h3 id="correlating-log-messages-from-openwrt-with-syslog-ng">Correlating log messages from OpenWRT with syslog-ng</h3>

<p>The central syslog server receives two type of log messages from each connection. One message from NEW events and another from DESTROY events. These two symbolize the beginning and the end of a session. I will use <strong>grouping-by()</strong> parser to correlate these messages into one context and get the session length metadata. The admin guide has a flow chart about how messages are added to the context and how it gets terminated. You may want to read that in advance.</p>

<p>The parser uses <strong>key()</strong> and <strong>scope()</strong> to build-up a context and identify which messages needs to be added to the context.</p>

<p>For specifying <strong>key()</strong> requires already parsed data. My setup can be translated to this: <strong>“Messages containing the same SRC, DST, SPT and DPT values from the ORIG part of the message belong to the same connection, unless they are not from the same host.</strong>”</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>parser p_correlate_session_data {
  grouping-by(
    key("${source.ip}/${destination.ip}/${source.port}/${destination.port}")
    scope("host")
    where(match("ORIG" value("MESSAGE")))
    trigger(match("DESTROY" value("MESSAGE")))
    having( "${UNIXTIME}@2" ne "1" )
    aggregate(
      value("event.start" "${ISODATE}@2")
      value("event.end" "${ISODATE}@1")
      value("event.duration", "$(- ${UNIXTIME}@1 ${UNIXTIME}@2)")
      value("MESSAGE" "Session completed; client='${source.ip}'; server='${destination.ip}'; destination_port='${destination.port}; protocol='${network.transport}'; session_lenght='${event.duration}'\n")
      inherit-mode("context")
    )
    inject-mode("pass-through")
    # destroy events sometimes arrive later than 2 minutes, even when a client app is already closed (ssh, telnet)
    timeout(600)
  );
};
</code></pre></div></div>

<p>The context will be closed and evaluated either when a message arrives which matches the filter specified in <strong>having()</strong> or the <strong>timeout()</strong> occurs.<br />
*Important! The timeout is currently set to 10 minutes. Connections longer than 10 minutes will set to 10 minutes in Elasticsearch.<br />
*</p>

<p>The evaluation will aggregate the context and creates new name-value pairs specified with <strong>values()</strong>. For example, it creates a new MESSAGE. This message is logged the same place where the received logs are stored. Actually I only need the parsed name-value pairs for Elasticsearch. The existence of this message indicates that everything is available. Therefore I will filter on this message later.</p>

<h2 id="configuring-dns-data-parsing-with-syslog-ngs-python-parser">Configuring DNS data parsing with syslog-ng’s Python parser</h2>

<p>*Note: the original post mentioned reverse DNS data but the script I used did not have a permissive license so I decided to abandon it. The current solution does not use reverse DNS anymore.<br />
*</p>

<p>Elasticsearch relies on DNS data. It parses the DNS packets by packetbeat but that is too heavy for OpenWRT. Lucky for us almost everything can be parsed from query logs of DNS server software like dnsmasq or unbound.</p>

<p>OpenWRT uses dnsmasq by default. You can turn on query logging in “<strong>DHCP and DNS → Server settings → General settings → Log queries</strong>”. That’s all.</p>

<p>Please note that I rather use <strong>unbound</strong> because of its support for DNS over TLS (DoT). The syslog-ng config I have for dnsmasq is pretty outdated but it can be easily updated with the example of unbound. Pull requests are welcome. ;)</p>

<p>DNS logs should be parsed further to get domain, tld, subdomain and regdomain, all the fancy stuff Elasticsearch supports. This is done by a python parser. Specifying the python parsers should look like this.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>parser p_unbound_csv {
    csv-parser(
        columns(question.ptid, syslog.level, source.ip, dns.question.name, dns.question.type, dns.question.class)
        delimiters(chars(' '))
        template("${MESSAGE}")
    );

    map-value-pairs(
        pair("event.action",                "dns-query")
        pair("destination.ip",              "172.18.0.10") # DNS server
        pair("event.category",              list("network"))
        pair("event.dataset",               "network.dns")
        pair("event.kind",                  "event")
        pair("event.module",                "network")
        pair("event.provider",              "unbound")
        pair("event.type",                  "info")
        pair("tags",                        list("syslog-ng"))
        pair("dns.type",                    "query")
        pair("network.direction",           "outgoing")
    );

    python(
        class("DNSSuffixResolver")
        options(
            "domain" "dns.question.name"
            "tld" "dns.question.top_level_domain"
            "subdomain" "dns.question.subdomain"
            "regdomain" "dns.question.registered_domain"
        )
    );
};
</code></pre></div></div>

<p><a href="https://publicsuffix.org/">Public Suffix List</a> is used to parse domain, tld, subdomain and regdomain from FQDNs. A python module with the same name is used by syslog-ng for the parsing. The database must be regurarly updated. Here is a simple cronjob to do that.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0 4 * * * curl https://raw.githubusercontent.com/publicsuffix/list/master/public_suffix_list.dat -o /usr/lib/python3.6/site-packages/publicsuffixlist/public_suffix_list.dat &amp;&gt;/dev/null
</code></pre></div></div>

<p>Both syslog-ng configuration and the parsers code are uploaded to <a href="https://github.com/abalage/balagetech-openwrt-syslog-ng-elasticsearch">GitHub</a>.</p>

<h2 id="configuring-geoip-enrichment-for-syslog-ng">Configuring GeoIP enrichment for syslog-ng</h2>

<p>Syslog-ng so as Elasticsearch relies on Maxmind’s GeoIP databases. You should register yourself to be able to periodically download the databases. I provided an example config. The most important parts are that the downloaded databases should be placed in /etc/syslog-ng. This way you do not have to adjust Apparmor settings.</p>

<h2 id="configuring-elasticsearch-to-ingest-logs-from-openwrt">Configuring Elasticsearch to ingest logs from OpenWRT</h2>

<p>Sending network traffic data of your home network from OpenWRT to syslog-ng is a great thing. But what is more cooler is to send it to Elasticsearch and create visualizations and reports. You can create nice visualizations once you have proper index template including <a href="https://www.elastic.co/guide/en/ecs/current/ecs-field-reference.html">ECS compatible</a> data type mapping. <span style="text-decoration: underline;">I emphasize that without this step Elasticsearch Security will not work at all.</span></p>

<h3 id="creating-an-index-template-for-network-events">Creating an index template for network events</h3>

<p>Explicit mapping should be created manually by using Elasticsearch’s PUT API. You can do this in <strong>Dev Tools → Console</strong>. If this is new to you, then you should check <a href="https://balagetech.com/visualizing-fail2ban-logs-in-kibana/#Create_index_template_for_Fail2ban_in_Elasticsearch">my previous step by step guide</a> about it.<br />
Because of the length of the mapping file I provide a downloadable version of the index template <a href="https://github.com/abalage/balagetech-openwrt-syslog-ng-elasticsearch/blob/master/elasticsearch/template-network.json">in the following file on GitHub</a>.</p>

<p>Please note that this mapping also specifies a template for the index names it will match on. In my case it is <strong>network-*</strong>.</p>

<h2 id="monitoring-my-home-network-with-examples">Monitoring my home network with examples</h2>

<p>I already created <a href="https://balagetech.com/simplified-logging-docker-elasticsearch-syslog-ng/#Creating_Docker_visualizations_in_Kibana">videos about how you can make different type of visualizations in Kibana</a>. You should definitely check the videos if you are stuck. Therefore this time I picked up two recent cases because I wanted to focus on what benefits I could get by having network data in Elastic.</p>

<h3 id="where-and-how-are-my-images-uploaded-by-using-a-web-printing-service">Where and how are my images uploaded by using a web printing service?</h3>

<p><strong>Update:</strong> The examples below used an older implementation and the attribute names are different from ECS mappings. However you can still get the idea.</p>

<p>I wanted to print dozens of family photos on paper. I decided to use CEWE’s service to do that. They even have a <a href="https://en.wikipedia.org/wiki/Qt_(software)">Qt based software</a> for Linux to place orders.</p>

<p>I wanted to feel secure as I am about to upload private data to someone else’s computer. Where are they uploaded? Are those services use HTTPS for transferring my precious family photos? Let’s find that out.</p>

<p><strong>Note: My actions did take place between 21:00 and 22:30 on March 17th, 2019.</strong></p>

<ul>
  <li>
    <p>In the browser’s address bar I noticed that registration and uploading takes place on “photoprintit” domains via HTTPS. Let’s check the traffic belonging to those domains. Using the following regex query <strong>outbound.destination.address:*photoprint*</strong> <a href="https://www.youtube.com/watch?v=apjwt1UK0xA">on the dashboard</a> gave me the following results.<a href="/assets/uploads/2019/03/kibana-photoprintit-1250.png"><img src="/assets/uploads/2019/03/kibana-photoprintit-625.png" alt="Kibana Dashboard showing traffic syslog from photoprintit domain via OpenWRT" /></a></p>
  </li>
  <li>
    <p>On the top left corner in <a href="https://www.youtube.com/watch?v=430TwfwnV3E">Coordinate Map visualization</a> we can see that all traffic goes to Germany (I am located in Hungary). As a result I checked the service’s <a href="http://www.foto-rossmann.hu/adatvedelem.html">Data Privacy document</a> which also shows that both their web site and the hosting is located in Germany. <a href="/assets/uploads/2019/03/kibana-photoprintit-geomap-1250.png"><img src="/assets/uploads/2019/03/kibana-photoprintit-geomap-625.png" alt="Kibana Geo Map photoprintit traffic" /></a>The service provider is a German company, however it is quite funny that I had to send my photos to Germany for printing so they will deliver them back to Hungary.</p>
  </li>
  <li>
    <p>Do they use HTTPS for the traffic? Let’s use a <a href="https://www.youtube.com/watch?v=IfKPcRIUSzc">Data Table visualization</a> to see that. It seems like that there are some traffic on 80, however most of the traffic goes to 443 (HTTPS).<a href="/assets/uploads/2019/03/kibana-photoprintit-datatable-1250.png"><img src="/assets/uploads/2019/03/kibana-photoprintit-datatable-625.png" alt="Kibana Data Table photoprintit traffic details" /></a></p>
  </li>
</ul>

<p>I did not have to do any extra work to get these information because GeoIP, <del>Reverse</del> DNS, traffic size and details are all there. As a result I could do the same exercise with any other web site.</p>

<h3 id="is-there-any-device-on-my-network-phoning-home">Is there any device on my network phoning home?</h3>

<p>Is there any network traffic going to a specified country, for instance<a href="/2019/04/27/android-app-phones-home-china/">is there anything going to China unattended</a>? (I could choose any other country.)</p>

<p><strong>Note: In the following examples I excluded a client host where I made explicit connections to Chinese websites. Data is from 11 day long period.</strong></p>

<ul>
  <li>
    <p>We can filter on a country by using <strong>outbound.destination.geo.country_name:China</strong>.<a href="/assets/uploads/2019/03/kibana-china-dashboard-1250.png"><img src="/assets/uploads/2019/03/kibana-china-dashboard-625.png" alt="Kibana Dashboard China details" /></a></p>
  </li>
  <li>
    <p>According to the results there are two devices which communicate to that country. The device <strong>tplink.lan</strong> is a WiFi Access Point running on OpenWRT. The other device <em>**</em><a href="https://balagetech.com/android-app-phones-home-china/#Case_1_Samsung_Galaxy_A5_2016">Galaxy-A5-2016.lan</a> is a smartphone connecting to that access point over WiFi.<br />
Let’ see the details on a different <a href="https://www.youtube.com/watch?v=IfKPcRIUSzc">Data Table visualization</a> again.<a href="/assets/uploads/2019/03/kibana-china-datatable-1250.png"><img src="/assets/uploads/2019/03/kibana-china-datatable-625.png" alt="Kibana Data Table visualization China traffic details" /></a></p>
  </li>
</ul>

<p>Apparently there are communication going outwards of my home network, however I still do not know what is inside of them. That WiFi Access Point used <a href="https://en.wikipedia.org/wiki/Network_address_translation">NAT</a> a couple of days ago until I disabled it, seems like there may be duplicate entries.</p>

<p>A logical next step would be to run tcpdump on OpenWRT parameterized to only capture and save TCP packets going on to those IP addresses. You can further analyze the packet captures  with other tools. But this is a topic of another post I will write later.</p>

<h2 id="verdict">Verdict</h2>

<p>I hope that with the help of this blog post anyone can monitor their home network with OpenWRT and syslog-ng and Elasticsearch.</p>

<p>If this post was helpful for you, then please share it. Even more should you have anything to ask then feel free to make any comments below. I will highly appreciate it.</p>]]></content><author><name>Balázs Németh</name></author><category term="syslog" /><category term="elasticsearch" /><category term="kibana" /><category term="network" /><category term="openwrt" /><category term="syslog-ng" /><summary type="html"><![CDATA[Monitor home network traffic with OpenWRT and Syslog-ng with Elasticsearch Security. I wanted to see what happens on my home network. Is there something going on I should be aware of? Is there any device which creates suspicious connections like phoning home? I will use OpenWRT and syslog-ng to get the answers and Elasticsearch Security to get the analytics.]]></summary></entry></feed>