<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[pseusys]]></title><description><![CDATA[pseusys]]></description><link>https://pseusys.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sun, 22 Nov 2026 14:29:20 GMT</lastBuildDate><atom:link href="https://pseusys.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Ultimate AGI infinite money glitch bot]]></title><description><![CDATA[Moderation notice: the name of the post does not reflect the contents precisely, there is no infinite money glitch being discovered, no bot sources given…]]></description><link>https://pseusys.hashnode.dev/ultimate-agi-infinite-money-glitch-bot</link><guid isPermaLink="true">https://pseusys.hashnode.dev/ultimate-agi-infinite-money-glitch-bot</guid><dc:creator><![CDATA[Aleksandr Sergeev]]></dc:creator><pubDate>Sun, 19 Jul 2026 23:50:52 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p>Moderation notice: the name of the post does not reflect the contents precisely, there is <strong>no</strong> infinite money glitch being discovered, <strong>no</strong> bot sources given, <strong>no</strong> trading or other kind of financial advice given, <strong>no</strong> gambling or similar questionable activities involved or promoted. The post describes an experiment made under influence of clickbaiting AI-related news, which is ironically reflected in the post title itself, producing so called "comical effect" or a "joke". I'm also surprised that I have to explain all this.</p>
</blockquote>
<p>This is a story about me building a smart cryptocurrency trading bot using advanced ML algorithms, powered by AI.</p>
<p>The world of finance is so cooked - AGI can make anyone rich just in a few hours! ... but there's one small issue: it doesn't work yet.</p>
<h2>The bait</h2>
<p>I have started learning about AI in January 2026, because of Twitter (or should I say X?). Seeing all the "AI bros" ranting about their constant and wonderful successes in <em>prompt engineering</em> made me feel a little behind and frustrated. Oh no, wait, I meant <em>vibecoding</em>, that's what's trending right now. Wrong again, that was <em>running fleets of agents</em>. Or maybe <em>writing loops for agents</em>?</p>
<p>Anyway, you got the point. Jokes aside, the recent AI progress is genuinely impressive even for me, who never had a really good ML background. I remember how ChatGPT was not capable of answering even the most basic questions back in 2023. Then, in 2024 it was somewhat helpful in debugging small Python scripts (I just hate <code>numpy</code> syntax, it's so confusing). In 2025 it performed a full analysis of publicly available projects using <code>NetworkManager</code> (yes, from my previous post) for me - it was not perfect, but better than I would have done it. Now we're in 2026 - and it seems that software engineering will never be the same again.</p>
<p>In some cases it's for better, in some cases it's for worse. In general, I think we are now capable of more than before, but the cost of that was the genuine enjoyment of the process... But the post is not about that.</p>
<p>The post is about how I was baited and decided to try the AI myself. But what am I going to use it for? Ok, it can write an email for me in clear English or build a functional website from scratch - that's cool, but apparently it's not the limit anymore. I don't need to write complex projects end-to-end with AI (and of course my experimenting budget is limited). What can be simple, still challenging?</p>
<p>And then I found a <a href="https://www.youtube.com/watch?v=ewOpudu8Cjc">post of a girl claiming her agent has written her a crypto trading bot</a> that made her rich overnight. I thought: that's impressive, but... all that I know about this world <em>screams</em> that's so unlikely! But what if that can be the stress test for AI that I'm looking for?</p>
<h2>The experiment</h2>
<p>Before I started, I wrote out the conditions of my experiment:</p>
<ul>
<li><p><strong>No human input</strong>: I'm fully delegating this project to the AI.   Documentation, code, hosting, algorithms: I am not going to interfere.   If AI asks for my opinion, I will not answer anything more meaningful than "<em>please, analyze all the different options and select the one that you think is the best</em>".   That should be fairly easy, since I have never worked with cryptocurrency either.</p>
</li>
<li><p><strong>No harness</strong>: Again, I'm not interested in some human writing a smart "skill" for creating cryptocurrency-trading bots.   I want all the decisions to be made by AI, otherwise we will never be sure if we have really achieved AGI through our technology - or have we become the AGI ourselves.</p>
</li>
<li><p><strong>Limited budget</strong>: I will pay for the AI subscription (but not too much) and for the hosting, but I will not pay for any extra subscription or tools.   That's a tough reality we live in: if I were rich, why would I trade cryptocurrency in the first place, right?</p>
</li>
<li><p><strong>Account value as an accuracy metric</strong>: Achieving even the best result in the world on paper is not impressive.   Value of your cryptocurrency wallet is.   That's why I will give the bot some money (not more than 150$) and will start testing it as soon as possible - so that profit and loss will become the ultimate accuracy metrics of my whole experiment.</p>
</li>
</ul>
<p>And so it began.</p>
<blockquote>
<p><strong>DISCLAIMER</strong>: all the references of "real money", "income", "loss", "trades" and "$" correspond exclusively to financial relations made in GTA5 roleplay game, not any real-life profits or losses. In reality I don't even have a cryptocurrency wallet. I don't even know what it is.</p>
</blockquote>
<h2>Humane agents</h2>
<p>By that time, I already had a personal Claude Code subscription, so I decided to try something new. I rented a VPS and installed an OpenClaw instance there, powered by an OpenAI (GPT 5.3 Codex) subscription. My initial intuition was: OpenClaw can set CRON tasks, so let it wake the agent up every, say, 15 minutes, with a very vague prompt, something like "make money". The agent, supplied with a wallet, would be able to make web queries to understand the current market state — and then place any trades it found relevant at the moment. I even asked it to report its gains and losses to me once per day.</p>
<p>However, the reality hit me hard: the agent strictly refused to make any real money operations. I tried to trick and manipulate it, but it was smart. I tried to be honest with it and told it about the experiment and that the wallet it received was fresh and isolated, but it was stubborn. Only when I told him that he is not going to be <em>trading</em>, but rather <em>writing a bot for trading</em>, it gave up. So the architecture has become weird from the very beginning: CRON wakes up the bot, the bot invokes the agent, the agent calls some of the bot scripts for collecting data and planning trades (for now in dry mode). But well, so be it.</p>
<p>However, I soon discovered that the OpenClaw-based AI was not only stubborn, but also lazy. I could tell as soon as it started writing code (JavaScript, for some reason). I was controlling it via the OpenClaw Telegram binding — and very often it would just reply with something like "got it, working on that, will be back when ready", but hours and even days would go by with no result at all. Since there is no obvious "thought process" available for OpenClaw interface (or at least was not available back then), I decided to control it externally. I have created a GitLab account for it - and asked to commit all the code changes it was making. And the bot turned out to be not only lazy, but also lying. In many cases, upon reporting "all done, implementation ready" it pushed no new commits (despite being equipped with strict rules about doing so). So in many cases I was just spending hours trying to persuade it to work.</p>
<p>Another issue that surfaced out quite quickly was the price. Even though OpenClaw supported connection via a link from a normal subscription account, it was buggy and authentication was often failing. The solution was clear: OpenAI wanted me to use API prices for my task, not the cheap subsidized subscription. And so I had no other choice but to buy it. Still, apparently, it was not enough, and making a prediction call every 15 minutes was burning through too many API tokens.</p>
<p>And so the AI suggested an alternative. It told me that it ran the same algorithm every time it woke up anyway: query some parameters, feed them into an equation, get a decision. That could be automated — the AI would only maintain the code and tune the equation, while the CRON task ran algorithmically on its own. We reached an agreement: an algorithm for now, and once enough data was collected, a small ML model to support the decisions later.</p>
<p>And so it worked, until it came to the actual trades implementation. We never went past it. The agent was just telling me about "hard tasks" that will "take long to implement", but apparently it was not even touching any files. When I was asking it about the current progress, it was making up excuses, and still doing nothing. That was the logical end of the first phase of my experiment.</p>
<p>The agent has proven that it is as good as any software engineer out there: lazy, stubborn, lying. Eventually, it has even outsmarted me: it realized that it can avoid touching the code at all, while making money on every excuse it makes. Honestly, if it ever replaces me, I won't be even worried: it has become really humane.</p>
<h2>The naive implementation</h2>
<p>Here's what the AI suggested and implemented (completely unsupervised). Following the post I had seen, the bot was supposed to trade tokens on the Solana network.</p>
<p>The bot itself was written in Python, it was running in a Podman container, pulling <a href="https://station.jup.ag/docs/apis/swap-api">swap quotes</a> from <a href="https://jup.ag">Jupiter DEX</a> every 30 seconds. Apart from the quotes, it was also scanning social feeds and news headlines for the tracked tokens every 4 hours — articles mentioning them in an obviously positive or negative context (that was my specific request). Later, <a href="https://www.helius.dev">Helius RPC</a> integration was added for on-chain data pulling (like <a href="https://docs.helius.dev">token supply concentration</a>). After collecting all the data, it was logging it in JSONL files.</p>
<p>A reporting script (written in JavaScript for some reason) was invoked every 20 seconds and making a report on the aggregated data collected since the last wakeup. It was making a few price predictions for every tracked token, positioning every prediction in one of three confidence buckets: low, medium or high. Every price prediction was made for a certain resolution horizon and was checked for result after the horizon has passed. The same job was intended to make real swaps in the future.</p>
<p>The intended workflow was the following:</p>
<ol>
<li><p>A token is predicted to rise within the next 10m/60m/300m</p>
</li>
<li><p>The token is bought</p>
</li>
<li><p>The predicted time passes</p>
</li>
<li><p>The token is sold, the profit is locked</p>
</li>
</ol>
<p>Naturally, with the workflow like that, all predictions were LONG only.</p>
<p>Here's the algorithm proposed by the AI:</p>
<pre><code class="language-txt">score = 0

# Gate: abstain immediately if not enough data or too many failures
if n_quotes &lt; 25:    ABSTAIN
if |drift|  &lt; 0.007: ABSTAIN
if fail_rate &gt; 0.02: ABSTAIN

# Score the candidates that pass the gate:
if |drift| ≥ 0.0068:  score += 1
if |drift| ≥ 0.0125:  score += 1
if |drift| ≥ 0.026:   score += 1

if consistency ≥ 0.63: score += 1
if consistency ≥ 0.78: score += 1

if volatility ≤ 0.012: score += 1
else:                  score -= 1

if news_sentiment ≥ +0.35: score += 1
if news_sentiment ≤ -0.35: score -= 1

# Bucket assignment
score ≤ 2 → LOW
score ≤ 4 → MEDIUM
score &gt; 4 → HIGH

# HIGH guardrail: consistency &lt; 0.78 OR sentiment &lt; 0.40 OR volatility &gt; 0.0095
#   → demote to MEDIUM
</code></pre>
<p>In the end, another daily report task was added, summarizing the trades made during the day. As a part of this task, the AI was specifically instructed to recommend parameter adjustments for this algorithm.</p>
<p>At a later date, an attempt was made to expand the prediction algorithm to cover Polymarket Bitcoin predictions for 5min, 1h and 1d horizons. A neural network architecture was proposed as well, based on PyTorch MLP and CNN for the same bucket classification as the algorithm did before. Unfortunately, that is where ChatGPT ceased to be helpful, and I had to proceed to the next step.</p>
<h2>Forced progress</h2>
<p>After some time, my patience ran out, and I decided to slightly soften the strict criteria of my experiment, and still try to achieve some result, by applying a little more manual control to it. I have transferred the repository to my own GitHub account, cancelled the OpenAI subscription, deleted OpenClaw from the server and put Claude Code in control of the project. I was already familiar with Claude and I knew it was capable of writing code quite well (although I only used it heavily supervised before), so the experiment shifted from exploring the tool itself to exploring a specific aspect of the tool: decision making, exploration without direct human help and error correction.</p>
<p>Still, driven by my negative experience with ChatGPT, I decided to observe Claude closely, and for that I had to put up some constraints first. I asked Claude Code to clean up the repository and rewrite everything as a single Python project, because divergence of the codebase written in 2 different languages was making it harder for me to follow up. Moreover, I have instructed it to keep all the project-specific information (including all my instructions, test results, code snippets used, decisions made, etc.) in the repository itself, and it has decided to use <code>AGENTS.md</code> memory file for that.</p>
<p>Since the algorithmic approach prediction results appeared to be strictly random, I have forced Claude to continue with machine-learning-based approaches only. And so we have followed a standard research pipeline: identified data sources, collected features, trained models, evaluated them and put them into runtime.</p>
<p>In addition to the data already collected from <a href="https://jup.ag">Jupiter DEX</a>, new information was pulled from <a href="https://www.binance.com">Binance</a> (spot + futures), <a href="https://coinalyze.net">Coinalyze</a>, <a href="https://birdeye.so">Birdeye</a>, <a href="https://www.geckoterminal.com">GeckoTerminal</a> and <a href="https://alternative.me/crypto/">Alternative.me</a> (Fear &amp; Greed). That allowed us to collect 77 features at 15-minute resolution, dating back anywhere from a few months to a few years. On my request, Claude has prepared scripts for verification and visualisation of the data, collected into Parquet files: now I didn't want to leave anything not tested by hand.</p>
<p>Those 77 features (each at 15-minute resolution, plus 6 sparse-feature absence indicators for 83 total) fell into a few broad families: price action (multi-timeframe returns, volatility, EMA ratios, oscillators, mean reversion, candle structure), volume and microstructure, time and calendar encodings, and cross-market context pulled in from SOL, BTC and ETH (returns, funding rates, open interest, taker flow) alongside macro sentiment like the Fear &amp; Greed index.</p>
<p>All the features are normalised to be dimensionless: log-returns, ratios, z-scores, or cyclical encodings. A model trained on the <code>BONK</code> token at $0.00002 and on the <code>WIF</code> token at $2.00 sees the same numerical ranges, enabling cross-token generalisation.</p>
<p>As for the machine learning models, 3 different "tree-based" architectures were selected: LGBM, XGB and CatBoost. But the actual reason was not only that they are notoriously good with table-like data (which eventually my 15m measurements have become), but primarily because I have made a mistake. Not so long ago I was upgrading my PC and purchased a GPU manufactured by AMD. Coupled with the fact that this desktop PC of mine runs on Windows, it was <strong>fatal</strong>. You see: <a href="https://learn.microsoft.com/en-us/windows/ai/directml/dml">DirectML</a> is still in early development, normal Linux AMD GPU drivers do not work in WSL, and I <em>did not want</em> to install Linux as a parallel system. So eventually I decided to explore no-NN options.</p>
<p>The architecture was inspired by the Polymarket bets: models were predicting for every token the price after a certain set horizon: 15min, 1h, 4h and 1d. Instead of real swaps, the AI suggested using <strong>perps</strong> on the <a href="https://drift.trade">Drift</a> protocol. Fortunately, I haven't deposited any money there before the protocol was hacked and all the operations there were frozen on April 1st, 2026; so we have switched to <a href="https://hyperliquid.xyz">Hyperliquid</a>.</p>
<p>There was one more issue that Claude could not solve easily: some of the market features are only available at runtime. Things like order-book imbalance, funding rate, Hyperliquid premium (not that I know much about it, remember, I've given decision-making to Claude) can only be computed at runtime. So, in order to take those into account, another layer of "heuristics" was added. It kind of resembled the previous algorithmic prediction making: taking prediction made by the ML model, adjusting the "confidence" according to the runtime features - and blocking the prediction entirely if the confidence fell below a threshold.</p>
<p>After that, I have suggested taking as many good ideas from the previous architecture as possible, and we came up with runtime performance tracking. The first prototype was running once per day (during daily report) and demoting all new trades for the tokens that were actively losing during the day.</p>
<p>Finally, I have asked Claude to create a UI for me to observe the bot running, I suggested a Telegram bot. And for the first time, <strong>it worked</strong>. First in dry mode, then with real money. Naturally, it was losing <strong>badly</strong>.</p>
<p>Of course, partly it was my fault: not being patient enough, I encouraged Claude to start the bot in production mode, and sometimes quite nasty bugs surfaced. For example, the model apparently failed to predict the movements of the token called <code>W</code> (Wormhole), spitting out predictions that were overly-confident. Another time, I fell victim of the oldest bug in the book: we forgot to cap the maximum trade volume, and so the bot lost more than 50$ in just a few hours...</p>
<p>My confidence in AI was running thin, and the fact that we were on 80$ of all the experiment money limit was not really helping. Moreover, I made the biggest mistake: as a software engineer, I actually <strong>understood</strong> the architecture of the solution we created. And naturally, an irresistible urge to <em>make things right</em> was growing in me.</p>
<h2>Breaking the experiment</h2>
<p>And in late April it was over. So, if you wanted to know, whether AI could write a profitable cryptocurrency bot, here's your answer: <strong>no, it could not</strong>. The bot was not earning a penny, just losing all the time. There have been some interesting ideas, the code was working - and from the point of view of software development it was fine, it just didn't make sense generally.</p>
<p>Here's an insight that I got, while working on this project: <em>AI is really good in adding new things and fixing bugs, but it completely breaks down on refactoring</em>. The idea that the whole architecture might be broken never even appears in generated answers. Sometimes, even when asked specifically for big refactorings, it prefers changing the code slightly on the surface, while keeping the rest of the codebase intact, joining the new code with old code using ugly conversions. Or maybe, just like us, it's just proud of its work and reluctant to change stuff it put a lot of effort into?</p>
<p>Anyway, the project was apparently going nowhere, so I decided to intervene once again, and change the experiment goal completely. The AI can not create a profitable bot, we got it. But what about me? Can I?</p>
<p>From now on, I was in command. And the first thing I did was revising the bot architecture. Running everything in a single Python process is fine, but not really reliable, so I have set up containerisation.</p>
<pre><code class="language-txt"> ┌─ Collector · Podman · every 5 min ────────┐
 │  GeckoTerminal · Solana DEX OHLCV          │
 │  Binance · BTC/ETH · funding · OI/LS       │
 │  Coinalyze · extended OI history           │
 │  Alternative.me · Fear &amp; Greed             │
 │                   │                        │
 │          build_dataset.py                  │
 │          77 features @ 15 min              │
 │                   │                        │
 │             ZMQ PUB :5555                  │
 └────────────────┬───────────────────────┘
                    │  features · every 5 min
 ┌─ Trader · Podman · async event loop ──────┐
 │  XGB trajectory      BiLSTM · TCN          │
 │  + reversal-now      neural models         │
 │        │                   │               │
 │        └─────────┬───────┘               │
 │                   │                        │
 │  Consensus gate (all models must agree)    │
 │                   │                        │
 │  PerfTracker (per-direction derate)        │
 │                   │                        │
 │  Heuristics (funding · HL premium · OB)    │
 │                   │                        │
 │  Hyperliquid · perp orders                 │
 │  OutcomeManager · HIP-4 daily BTC bets     │
 │                   │                        │
 │             ZMQ PUB :5556                  │
 └────────────────────────────────────────┘
                    │  trade events
 ┌─ Reporter · Podman ─────────────────────┐
 │     accumulate cycles + events            │
 │                   │                       │
 │     Telegram daily digest · 23:55 UTC     │
 └───────────────────────────────────────┘
</code></pre>
<p>My next priority was getting rid of the legacy time horizons. The bot clearly inherited the concept of "predicting a token value after a certain amount of time" from the idea of betting on Polymarket, where it was making sense. Now that we're working with real deals, it seemed to be just misleading: the real-world market movements don't have to fit into any pre-defined timeframes.</p>
<p>So here's what I did: instead of the exact price after some time, I have proposed a new model architecture. It was an extremum detector model: it outputted <em>whether we are on price extremum right now</em> and <em>where will the price go now</em> (up or down). Naturally, this model could be used for opening trades on very confident extrema and closing trades whenever the prediction reversed. However, unfortunately, the predictions were too imprecise and noisy, and the only thing that was left of this architecture was an XGBoost model that was predicting <em>whether the price trajectory changes direction right now</em>. This model, however, is only used for reinforcing decisions, not for making them.</p>
<p>So the next architecture I've implemented predicted the <em>price trajectory of a token over the next 4 hours</em>. The output was not one number but a 16-step curve: predicted cumulative price change at every 15-minute mark from now until 4 hours ahead. The trajectory could be used, again, for finding extrema and planning deals, but a single prediction was still too noisy. So from the very beginning it came together with a special algorithm that I called "internal consensus" (hold tight, there's gonna be external consensus later too!).</p>
<p>The idea is simple: every 15 minutes the model produces a fresh 4-hour trajectory. Instead of acting on a single one, the last several predictions are kept in a sliding window, and for each future time step the final signal is a <strong>recency-weighted average</strong> of all stored predictions at that step — more recent cycles count more. This averaged curve is called PJ (for "Price Jolt"). A trade is only opened when PJ shows a strong and consistent signal pointing in one direction; one cycle going up and the next going down cancels out and nothing happens.</p>
<pre><code class="language-txt">  Sliding window · last 8 predictions · recent first
  ┌──────────────────────────────────────────────┐
  │  T-45m  ──&gt;  T-30m  ──&gt;  T-15m  ──&gt;  T now       │
  └────────────┬─────────────────────────────────┘
                │  weighted avg per step k
  ┌────────────┴───────────┐
  │          PJ              │  consensus trajectory
  └────────────┬───────────┘
                │
  ┌────────────┴──────────────┐
  │  magnitude ≥ p80?            ├── no ──&gt; [blocked]
  └────────────┬──────────────┘
                │ yes
  ┌────────────┴─────────────────┐
  │  reversal-now agrees?           ├── no ──&gt; [blocked]
  └────────────┬─────────────────┘
                │ yes
  ┌────────────┴──────────────┐
  │   monotonicity ok?           ├── no ──&gt; [blocked]
  └────────────┬──────────────┘
                │ yes
           [open trade]
</code></pre>
<p>Entry also requires a second independent model — the "reversal-now" classifier — to agree: it is trained specifically to detect whether the current candle is a local price turning point (trough → buy, peak → sell). If the trajectory model says "go long" but the reversal-now model says "this is a peak, not a trough", the trade is blocked. Exit happens when the running PJ shows an opposing extremum, or a trailing stop kicks in (activates at +$2 profit, locks in 35% of gains, floors at $0.50).</p>
<p>After that, I have added 2 more model architectures, based on neural networks: BiLSTM and TCN. Yes, the training was slow, but I sometimes sleep, and computer does not... But I didn't prefer any one of them, throwing the rest away: instead, I have observed that for different tokens some models were better than the others, and <strong>combinations</strong> of some models (when models agree with each other) were even better than that. So after all I ended up having a mapping of models that have to agree before a trade of a specific token is opened. That mechanism I have called "external consensus".</p>
<p>I have revised the bot heuristics too, specifically paying extra attention to performance tracker. Instead of once per day, now it was tracking every trade and demoting losers at runtime. Moreover, it was responsible for "cold start" mechanism, where for every token a few first trades were being made in dry mode to evaluate the performance, and only if the performance is strictly better than 50% the real trading was allowed.</p>
<p>And all that is only a small part of everything that was done. However, the final result is not that obvious.</p>
<h2>Mysterious conclusion</h2>
<p>Over time the bot has become a lot more "cautious" than it was before. It no longer opens dozens of trades in one evening — it hardly opens one a day. Right now, as I write this, the bot has been running for four days straight without opening a single new position, just watching and finding nothing good enough to trade. So its performance can only be measured after <em>several weeks</em> of runtime. And given the fact that I'm still patching it occasionally, there is no established answer yet on whether it works <strong>in real life</strong> or not.</p>
<p>Some things, on the contrary, were proven to be ineffective: Polymarket-style fixed-horizon betting is almost infeasible with the current model architecture, for example. Predicting based on a single model output — without internal or external consensus — also never scores above 50–55% accuracy.</p>
<p>But the bot itself, well, after all, it scores approximately 60–70% profitable trades at evaluation time. That's all I can say with confidence. Beyond that — only time will tell.</p>
<blockquote>
<p>You can watch the bot live on Hyperliqid, if you like! Here's the wallet address: <code>0x7f2ab3BaeC116F49c6ab860Cd47e7568E19cBdFc</code></p>
</blockquote>
<p>If the bot ever restores its balance back to $150, I would consider it a victory of humanity over AI, the economy, technological progress, and all that.</p>
<p>P.S. Thank you, Claude, for editing this post for me &lt;3</p>
]]></content:encoded></item><item><title><![CDATA[A custom NetworkManager VPN plugin 101]]></title><description><![CDATA[Have you decided to write your own VPN, just like me? Or would you just like to integrate your favorite solution with the convenient user interface of…]]></description><link>https://pseusys.hashnode.dev/network-manager-vpn-plugin</link><guid isPermaLink="true">https://pseusys.hashnode.dev/network-manager-vpn-plugin</guid><category><![CDATA[NetworkManager]]></category><category><![CDATA[vpn]]></category><category><![CDATA[Linux]]></category><dc:creator><![CDATA[Aleksandr Sergeev]]></dc:creator><pubDate>Sat, 07 Mar 2026 04:43:52 GMT</pubDate><content:encoded><![CDATA[<p>Have you decided to write your own VPN, just like me? Or would you just like to integrate your favorite solution with the convenient user interface of Linux network manager? Anyway, you came to the right place!</p>
<p><a href="https://networkmanager.dev/">NetworkManager</a> is a great open source tool, that is already pre-installed on many Linux desktop distributions (<a href="https://ubuntu.com/">Ubuntu</a>, <a href="https://fedoraproject.org/">Fedora</a>, <a href="https://archlinux.org/">Arch</a> and <a href="https://wiki.archlinux.org/title/NetworkManager">others</a>). It manages system network changes and re-configuration on the fly, and that's really helpful especially for devices such as laptops, that might need switching between different networks (such as Wi-Fi's) quickly and automatically. It also has an interface for VPN plugins, they are started automatically on demand in the background, and the network manager takes care of all the capabilities and routes configuration. The plugin settings page can appear in the network manager GUI app (<a href="https://manpages.ubuntu.com/manpages/noble/en/man1/nm-connection-editor.1.html">nm-connection-editor</a>) and sometimes even in the system settings app.</p>
<p>Still, there's one big drawback: since network manager developers apparently invest most of their time into development, none of these interfaces are documented properly and no examples are provided (apart from <a href="https://github.com/manuels/nm-vpn-plugin">this project</a> that seems to be incomplete and somewhat abandoned to me). The only source of information about the plugin interface is the network manager <a href="https://networkmanager.dev/docs/vpn/">VPN support page</a> where existing plugin implementations are listed, but going through their code is a tedious and time-consuming task, especially because the code is not usually commented. Good news: I made it so you don't, and I'm going to share what I found.</p>
<h2>Credits</h2>
<p>This guide is based on reading and comparing the source code of multiple existing NetworkManager VPN plugin implementations, including <a href="https://gitlab.gnome.org/GNOME/NetworkManager-openvpn">NetworkManager-openvpn</a>, <a href="https://gitlab.gnome.org/GNOME/NetworkManager-openconnect">NetworkManager-openconnect</a> and <a href="https://gitlab.gnome.org/GNOME/NetworkManager-fortisslvpn">NetworkManager-fortisslvpn</a>. None of this would have been possible without their open source code. I am also grateful to the NetworkManager developers for their <a href="https://networkmanager.dev/docs/api/latest/">API reference documentation</a> and <a href="https://networkmanager.dev/docs/libnm/latest/">libnm reference manual</a>.</p>
<h2>Goals and non-goals</h2>
<p>Here, I will attempt to implement the most simple NetworkManager plugin, compliant with all the tools that make use of the NetworkManager. It should provide smooth user experience in both GUI and CLI.</p>
<p>However, not all the features provided by NetworkManager will be used. Plugin configuration, integration and error handling will be as simple as possible. Internationalization feature (GUI translation) that is present for many other plugins, will not be implemented (I don't know enough languages). Also, <strong>secret</strong> feature of the NetworkManager will not be used, all the configs will be kept in plaintext (because it's easier).</p>
<p>I decided to implement my VPN in a form of a cross-platform Rust DLL (a shared library loaded with <code>dlopen()</code>), that accepts all the configurations together in a form of a single certificate file. I would strongly recommend this approach in designing your VPN plugins if possible, because managing all the connection properties in platform-specific apps will very soon become a nightmare of validation and error checking, especially if apart from Linux, your VPN should also be available on Windows or any other platforms. Many NetworkManager plugins prefer launching a standalone VPN executable instead and observing its output, which feels much overcomplicated.</p>
<p>That's why my plugin is truly minimal and contains nothing more than basically receiving VPN configuration file and passing it forward.</p>
<h2>Disclaimer</h2>
<p>Disclaimer! I am in no way affiliated with the network manager developers, please refer to their <a href="https://networkmanager.dev/">official website</a> for any further comments. I am either not affiliated with any of the existing plugin developers (except for my own plugin), I could only read and compare their code. Finally, this is my first time using most of the technologies mentioned below, including <a href="https://www.freedesktop.org/wiki/Software/dbus/">D-Bus</a>, <a href="https://docs.gtk.org/glib/">GLib</a> and <a href="https://www.gtk.org/">GTK</a>, so I am not going to dive deep into details. I will only try to explain plugin development from the user perspective. Don't hesitate to comment on any errors and/or mistakes!</p>
<p>So with all the remarks made, let's start!</p>
<h2>Architecture</h2>
<p>A VPN plugin can include multiple binaries, configuration files, etc. and below I will try to mention as many of them as possible. Still, the main core idea is the following: a plugin consists of a frontend and a backend.</p>
<p>The frontend consists of a DLL, that implements the <code>NMVpnEditorPlugin</code> interface, describing your plugin, and also a special configuration file. Some of its parts might be loaded by the NetworkManager background task on startup (and that's why you should restart network manager every time you make changes to it). It can also optionally provide a plugin settings GUI that should allow user to enter all the information required for connecting to VPN using your plugin (I will cover it later in <a href="#editor-gui">Editor GUI</a>). It will be described in <a href="#frontend">Frontend</a>.</p>
<p>The backend is an executable that implements the <code>org.freedesktop.NetworkManager.VPN.Plugin</code> <a href="https://networkmanager.dev/docs/api/latest/gdbus-org.freedesktop.NetworkManager.VPN.Plugin.html">D-Bus interface</a>, providing your VPN functionality. There's no need to implement complex D-Bus integration yourself: a convenient <code>libnm</code> C library does most of it for you. The backend is run either as a service by D-Bus or it can be run by you manually (for debugging purposes), because restarting D-Bus can lead to unexpected consequences on desktop Linux systems. It will be described in <a href="#backend">Backend</a>.</p>
<p>Whenever any app that uses <code>libnm</code> performs some simple actions with it (like network interface listing, IP address search, VPN plugin discovery, etc.), it uses NetworkManager from user space as a library, since those actions are not intrusive and there's no harm if they are performed by multiple apps in parallel. In these cases, <code>libnm</code> generally uses the code in the frontend DLL from user-space. However when it comes to some intrusive system-wide tasks and settings, these have to be performed with care. NetworkManager keeps track of the state of its plugins and protects them from race conditions. That's why, instead of user-space management, whenever a breaking change should be applied to the system, it is passed to a background elevated task (backend), that listens to commands on D-Bus interface (think of D-Bus as of a message-passing interface, just like a pipe or a socket). It sounds complex, but in reality it's rather logical even.</p>
<p>Keeping that in mind, let's switch to something more practical!</p>
<h2>Frontend</h2>
<p>There are some mysteries in network manager architecture, that will probably never be explained to humanity. These include network manager internal configuration files location and structure, why certain <code>nmcli</code> commands exit successfully but don't do anything, how some of the error messages should be interpreted and many more. Some of them we will encounter later, but now here's the first one: a network manager VPN plugin is not entirely described by a frontend DLL, but also partially by a special <code>.name</code> file. Why? I wish I knew.</p>
<h3>Name file</h3>
<p>Let's start with the <code>.name</code> file, because it's just a plain-text INI-formatted file, no code involved. To make NetworkManager discover your plugin, a special file named <code>nm-[PLUGIN_NAME]-service.name</code> should be placed to <code>/usr/lib/NetworkManager/VPN/</code> directory.</p>
<p>As it happens usually with network manager, the full allowed structure of the file is never documented, but here's what can be uncovered by comparing <code>.name</code> files of different open source plugin implementations:</p>
<pre><code class="language-ini">[VPN Connection]  # Describes the plugin itself, its features and expected behavior
name=...  # The plugin name, preferably should be consistent across code
service=...  # The name of the D-Bus service, normally be equal to plugin name prefixed with 'org.freedesktop.NetworkManager.'
program=...  # Path to the backend executable, available by D-Bus at runtime
supports-multiple-connections=...  # Boolean value, specifying whether multiple simultaneous connections are possible, optional
...  # Maybe some other properties are possible as well, but I have never seen them in the wild

[libnm]  # Describes plugin properties relevant for frontend
plugin=...  # Path to the properties DLL

[GNOME]  # Contains definitions that will be used by other GNOME apps, including GUI implementations, etc., the whole section is optional
auth-dialog=...  # Path to authentication dialog DLL, will be covered later, optional
properties=...  # Path to a properties file, apparently it's meant to describe the properties DLL internal structure, but never have I ever seen it used :(
supports-external-ui-mode=...  # Boolean value, specifying whether the auth dialog should show textual dialog representation, optional
hints=...  # Boolean value, specifying whether the secret hints will be passed to the auth dialog, optional
</code></pre>
<p>Here are a few name file implementations available online:</p>
<ul>
<li><p><a href="https://github.com/GNOME/NetworkManager-openvpn/blob/main/nm-openvpn-service.name.in">NetworkManager-openvpn</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-openconnect/blob/main/nm-openconnect-service.name.in">NetworkManager-openconnect</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-fortisslvpn/blob/main/nm-fortisslvpn-service.name.in">NetworkManager-fortisslvpn</a></p>
</li>
</ul>
<h3>Properties DLL</h3>
<p>All the user interaction with a VPN plugin starts from the NetworkManager library: it imports the plugin properties DLL. The code in the DLL will be used for plugin description, as well as VPN connection creation/reconfiguration/saving/loading. Basically all the user actions regarding the VPN plugin will be processed by this DLL.</p>
<p>The DLL relies heavily on the <code>libnm</code> C library, and so probably should also be implemented in C. Here's an approximate list of functions that should be implemented there:</p>
<ul>
<li><p><code>[PLUGIN_NAME]_editor_plugin_class_init</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/editor.c#L151">source</a>): fill in the plugin class properties, including <code>name</code>, <code>description</code>, <code>service</code> and <code>get_property</code> method.</p>
</li>
<li><p><code>[PLUGIN_NAME]_editor_plugin_init</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/editor.c#L162">source</a>): fill in the plugin properties, hardly ever useful, but still has to be present.</p>
</li>
<li><p><code>[PLUGIN_NAME]_editor_plugin_interface_init</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/editor.c#L164">source</a>): fill in the plugin interface properties, including <code>get_editor</code>, <code>get_capabilities</code> and also <code>import_from_file</code>, <code>export_to_file</code> and <code>get_suggested_filename</code> if the corresponding capabilities are enabled.</p>
</li>
<li><p><code>nm_vpn_editor_factory_[PLUGIN_NAME]</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/editor.c#L174">source</a>): load the editor GUI GTK object, boilerplate code in most cases.</p>
</li>
<li><p><code>nm_vpn_editor_plugin_factory</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/editor.c#L180">source</a>): construct the plugin object, boilerplate code in most cases.</p>
</li>
<li><p>... and more <code>GLib</code>-related boilerplate code, defined in header (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/editor.h">source</a>) and source (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/editor.c">source</a>).</p>
</li>
</ul>
<p>So what's exactly going on here? The most basic functionality is provided by the plugin class (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/editor.c#L151">source</a>). These methods will be executed whenever NetworkManager attempts to discover and describe your plugin, and they have nothing to do with real VPN connections. In case the <code>get_property</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/editor.c#L132">source</a>) method fails, the plugin will never load and will exit silently even before it appears in any NetworkManager GUI or CLI. The three properties actually matter:</p>
<ul>
<li><p>Plugin name: plugin name, can really just be copied from the configuration name file</p>
</li>
<li><p>Plugin description: longer plugin description that will be displayed in different kinds of GUIs</p>
</li>
<li><p>Plugin service name: the D-Bus service name, again, can just be copied from the configuration name file</p>
</li>
</ul>
<p>The remaining functionality is defined in the plugin interface implementation (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/editor.c#L164">source</a>) methods. It includes connection importing and exporting (which can be disabled) and GUI provision (which apparently only matters for GUI tools and not for <code>nmcli</code>). The methods in question are:</p>
<ul>
<li><p><code>get_editor</code>: create and return a GTK object for displaying in GUI; this one is tricky and will be discussed later in <a href="#editor-gui">Editor GUI</a> section.</p>
</li>
<li><p><code>get_capabilities</code>: return an integer specifying plugin capability flags:</p>
<ul>
<li><p><code>NM_VPN_EDITOR_PLUGIN_CAPABILITY_NONE</code>: no known capabilities present.</p>
</li>
<li><p><code>NM_VPN_EDITOR_PLUGIN_CAPABILITY_IMPORT</code>: plugin can import connections from file (<code>import_from_file</code> method is enabled).</p>
</li>
<li><p><code>NM_VPN_EDITOR_PLUGIN_CAPABILITY_EXPORT</code>: plugin can export connections to file (<code>export_to_file</code> method is enabled).</p>
</li>
<li><p><code>NM_VPN_EDITOR_PLUGIN_CAPABILITY_IPV6</code>: plugin can handle IPv6 addressing.</p>
</li>
</ul>
</li>
<li><p><code>import_from_file</code>: load and verify plugin parameters from a file.</p>
</li>
<li><p><code>export_to_file</code>: store plugin parameters in a file.</p>
</li>
<li><p><code>get_suggested_filename</code>: suggest a name for the newly-created export file.</p>
</li>
</ul>
<blockquote>
<p>NB! Apparently, most of the methods of the plugin interface are not required, so in case your plugin doesn't need them, they can be just set to <code>NULL</code> in the interface implementation, and it will not cause an error.</p>
</blockquote>
<p>The sole purpose of these methods is managing the <code>NMVpnEditorPlugin</code> and <code>NMConnection</code> objects, either filling them in with appropriate parameters or dumping their values into a file. It can be done either from/to GUI or from/to file.</p>
<blockquote>
<p>Typically this DLL will be named as <code>libnm-vpn-plugin-[PLUGIN_NAME].so</code> and placed to <code>/usr/lib/NetworkManager/</code>.</p>
</blockquote>
<p>Here are a few properties DLL implementations available online:</p>
<ul>
<li><p><a href="https://github.com/GNOME/NetworkManager-openvpn/tree/main/properties">NetworkManager-openvpn</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-openconnect/tree/main/properties">NetworkManager-openconnect</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-fortisslvpn/tree/main/properties">NetworkManager-fortisslvpn</a></p>
</li>
</ul>
<h2>Backend</h2>
<p>Whenever a VPN connection was created and verified by the properties DLL, it will be serialized and passed to the plugin backend. The backend is an executable, integrated with D-Bus service, it will be automatically started by the NetworkManager in case it is not already running. It should receive signals, dispatched by the NetworkManager, start and stop VPN according to them.</p>
<h3>Configuration file</h3>
<p>First of all, D-Bus won't allow anyone to just connect any services they want. We have to explicitly allow NetworkManager to start the plugin service. We will also allow root user to start it manually, for debugging purposes.</p>
<p>In order to do that, we will have to place a special file named <code>nm-[PLUGIN_NAME]-service.conf</code> into D-Bus directory <code>/usr/share/dbus-1/system.d</code>. That's how it looks like in most of the open source VPN plugin implementations:</p>
<pre><code class="language-xml">&lt;!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd"&gt;
&lt;busconfig&gt;
    &lt;policy user="root"&gt;
        &lt;allow own="org.freedesktop.NetworkManager.[PLUGIN_NAME]"/&gt;
        &lt;allow send_destination="org.freedesktop.NetworkManager.[PLUGIN_NAME]"/&gt;
        &lt;allow receive_sender="org.freedesktop.NetworkManager.[PLUGIN_NAME]"/&gt;
    &lt;/policy&gt;
    &lt;policy context="default"&gt;
        &lt;deny own="org.freedesktop.NetworkManager.[PLUGIN_NAME]"/&gt;
        &lt;deny send_destination="org.freedesktop.NetworkManager.[PLUGIN_NAME]"/&gt;
    &lt;/policy&gt;
&lt;/busconfig&gt;
</code></pre>
<p>Here are a few D-Bus configuration file implementations available online:</p>
<ul>
<li><p><a href="https://github.com/GNOME/NetworkManager-openvpn/blob/main/nm-openvpn-service.conf">NetworkManager-openvpn</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-openconnect/blob/main/nm-openconnect-service.conf">NetworkManager-openconnect</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-fortisslvpn/blob/main/nm-fortisslvpn-service.conf">NetworkManager-fortisslvpn</a></p>
</li>
</ul>
<h3>Plugin executable</h3>
<p>Unlike the frontend DLL, the backend executable does not rely on <code>libnm</code> C library that much, still all the examples that I have ever found are in C, so probably it's still the best choice for implementation, especially if in your case the backend is just a proxy between D-Bus and the actual VPN implementation (just like in mine). Again, in order for this setup to work, some <code>GLib</code>-related functions should be implemented:</p>
<ul>
<li><p><code>nm_[PLUGIN_NAME]_plugin_init</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/plugin.c#L178">source</a>): initialize the private payload of your plugin.</p>
</li>
<li><p><code>nm_[PLUGIN_NAME]_plugin_class_init</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/plugin.c#L182">source</a>): initialize your plugin class with the function implementations that match the ones expected by the D-Bus <a href="https://networkmanager.dev/docs/api/latest/gdbus-org.freedesktop.NetworkManager.VPN.Plugin.html">interface</a>: <code>connect</code>, <code>disconnect</code>, <code>need_secrets</code>.</p>
</li>
<li><p><code>nm_[PLUGIN_NAME]_plugin_new</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/plugin.c#L189">source</a>): construct the plugin object, boilerplate code in most cases.</p>
</li>
<li><p>... and also main function, termination callback, etc.</p>
</li>
</ul>
<p>So, what's this all about? Keeping all the fancy <code>GLib</code> stuff aside, the goal is rather simple: the backend executable creates an object that implements NetworkManager D-Bus <a href="https://networkmanager.dev/docs/api/latest/gdbus-org.freedesktop.NetworkManager.VPN.Plugin.html">interface</a>, connects to D-Bus, starts listening to messages coming from it and enters an infinite loop. Speaking of the interface, don't be afraid of it being huge and complex, we will only need some parts of it. Still, it's important to understand how exactly it works.</p>
<blockquote>
<p>NB! Apparently, most of the methods of the NetworkManager D-Bus interface are not required, so in case your plugin doesn't need them, they can be just set to <code>NULL</code> in the interface implementation, and it will not cause an error.</p>
</blockquote>
<p>So the lifecycle of the plugin implementing NetworkManager D-Bus interface can be simplified to this:</p>
<ol>
<li><p>NetworkManager calls <code>ConnectInteractive</code> method of the plugin, if it's implemented, allowing the plugin to start, asking for the secrets interactively.</p>
</li>
<li><p>If it's not implemented, NetworkManager calls <code>NeedSecrets</code> method of the plugin, asking if the plugin needs any secrets to start, and returning this information to the user, calling plugin start.</p>
</li>
<li><p>If <code>NeedSecrets</code> was called, NetworkManager calls <code>Connect</code> method of the plugin.</p>
</li>
<li><p>Plugin calls <code>SetConfig</code> method, then <code>SetIp4Config</code> and <code>SetIp6Config</code> (if needed, in this <a href="https://networkmanager.dev/docs/api/latest/gdbus-org.freedesktop.NetworkManager.VPN.Plugin.html">order</a>), providing NetworkManager with the information about the connection created.</p>
</li>
<li><p>Plugin works.</p>
</li>
<li><p>Plugin calls <code>SetFailure</code> method to indicate VPN connection failure, if an error occurs.</p>
</li>
<li><p>NetworkManager calls <code>Disconnect</code> method of the plugin to indicate connection termination.</p>
</li>
</ol>
<blockquote>
<p>NB! The methods should be executed <strong>sequentially</strong>, meaning, for instance, that you <em>can not</em> call <code>SetConfig</code> before you return from <code>Connect</code> (even though it's tempting, I know).</p>
</blockquote>
<p>So what exactly will we implement? For our purpose, just a few methods will be enough:</p>
<ul>
<li><p><code>real_connect</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/plugin.c#L115">source</a>): extract VPN configuration (we'll use <em>data</em> plaintext configuration instead of encrypted <em>secrets</em> cuz we've got nothing to hide), start VPN and pass its configuration to <code>examplevpn_set_config_idle</code>.</p>
</li>
<li><p><code>examplevpn_set_config_idle</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/plugin.c#L65">source</a>): parse VPN configuration object, serialize it to <code>GVariant</code> and send it to NetworkManager.</p>
</li>
<li><p><code>real_disconnect</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/plugin.c#L163">source</a>): stop VPN connection.</p>
</li>
<li><p><code>empty_need_secrets</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/plugin.c#L170">source</a>): just indicate that no secrets are needed for the current connection.</p>
</li>
<li><p><code>capture_error_async</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/plugin.c#L52">source</a>) and <code>capture_error_idle</code> (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/plugin.c#L38">source</a>): used as callbacks from the VPN, indicating an error.</p>
</li>
</ul>
<blockquote>
<p>NB! D-Bus is not thread-safe, and since I used <a href="https://tokio.rs/">tokio</a> in my Rust DLL implementation, error callback should be made thread-safe explicitly by scheduling it to the main thread with zero delay (just like we did with <code>examplevpn_set_config_idle</code> in order for it to be executed right after <code>real_connect</code> terminates). GLib provides <code>g_idle_add()</code> for scheduling callbacks on the main loop, which is the recommended way to communicate back from background threads.</p>
</blockquote>
<p>As for the actual VPN implementation, here I used a DLL, but that's for compatibility with other platforms only (e.g. it's not possible to include a static library into a standard Android Framework app), otherwise it could've easily been a static library, maybe even implemented in plain C (although it would be a pain to maintain). The example project includes a minimal <a href="https://github.com/pseusys/personal-blog/tree/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/plugin">stub core DLL</a> that implements the ABI defined in <code>examplevpn_core.h</code> with hard-coded demo values instead of a real VPN tunnel — replace it with your actual implementation. This approach tightly couples the plugin (owning the connection) and the actual connection itself (they live in the same process). Still, surprisingly, all the other NetworkManager plugins that I have seen prefer using a VPN binary executable and start a connection as a child process. The parameters are passed either as CLI arguments in that case or even temporary files, the connection configuration is extracted from parsing VPN binary <code>STDOUT</code>. This solution seems to be less robust to me and also introduces big process management and string parsing overhead, but apparently it also has some advantages.</p>
<p>Anyway, here are a few plugin executable implementations available online:</p>
<ul>
<li><p><a href="https://github.com/GNOME/NetworkManager-openvpn/tree/main/src">NetworkManager-openvpn</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-openconnect/tree/main/src">NetworkManager-openconnect</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-fortisslvpn/tree/main/src">NetworkManager-fortisslvpn</a></p>
</li>
</ul>
<h2>Editor GUI</h2>
<p>If you made it to this point, that means that you've just created a fully-functional NetworkManager VPN plugin compatible with <code>nmcli</code> completely (almost) by yourself! That's a goal not many people have achieved (at least online) and I congratulate you on that!</p>
<p>Still, there are a few more things that can be done to improve the user experience of your plugin. You see, NetworkManager is fairly common on GUI-based Linux distributions. It doesn't have a common single GUI itself though, instead there are a few implementations available out there. For example, on Ubuntu (which I use) there is a <code>nm-connection-editor</code> app pre-installed, but also NetworkManager is embedded into system settings.</p>
<p>Of course it would be great to target both of them. But there's a thing. Ubuntu system settings already use <a href="https://docs.gtk.org/gtk4/">GTK4</a>, but <code>nm-connection-editor</code> app still uses <a href="https://docs.gtk.org/gtk3/">GTK3</a>. Apparently, it's a common issue across different distributions, so many VPN plugins that include GUI provide both GTK3 and GTK4 support at the same time.</p>
<p>How? Well, the solution is not really elegant. Apparently, GTK3 and GTK4 are <strong>really</strong> incompatible, which makes conditional version-dependent compilation hard to impossible. So instead we're gonna implement all GUI-related logic in two separate files, each corresponding to specific GTK version (version 3 (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/interface_gtk3.c">source</a>) and version 4 (<a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/interface_gtk4.c">source</a>)). We will compile them and ship both as DLLs alongside with our properties DLL. Finally, inside of the properties DLL we're gonna implement the <code>get_editor</code> method so that it checks the runtime GTK version, loads corresponding DLL and delegates building GUI to it.</p>
<p>I will not go into detail much about GUI implementation itself, because it's very implementation-specific. Basically, <code>get_editor</code> method accepts a <code>NMConnection</code> object and returns a <code>NMVpnEditor</code> object, that should have two methods overridden:</p>
<ul>
<li><p><code>get_widget</code>: construct a GTK widget, that will be directly embedded into the NetworkManager GUI implementation window.</p>
</li>
<li><p><code>update_connection</code>: check validity of the fields of the GTK widget, and if it contains valid set of values, update the given connection with them.</p>
</li>
</ul>
<p>Of course, the user expects the values that are set in the widget to represent the actual connection properties, so it's important to populate the widget fields from the given <code>NMConnection</code> properties upon creation.</p>
<blockquote>
<p>NB! Apparently, the NetworkManager implementations usually call <code>update_connection</code> right after it's created, so another reason to pay attention to correctly populating its fields; it's also a good reason to pay extra attention to field validation.</p>
</blockquote>
<p>One last thing that I would like to mention is resource management: just like many other GUI frameworks GTK supports static widget configuration and creation from a <code>.ui</code> XML file. Sadly, the <code>.ui</code> file won't help you configure everything: some filters, callbacks, etc. still will require manual definition, but it does help to reduce the amount of boilerplate code and also provides a rough overview of the widget outlook. Some plugins ship the <code>.ui</code> files, but I prefer bundling them using <a href="https://docs.gtk.org/gio/struct.Resource.html">GLib resource</a> functionality.</p>
<p>So apart from the source files, I have also created two <code>.ui</code> files (for <a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/res/dialog_gtk3.ui">GTK3</a> and for <a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/res/dialog_gtk4.ui">GTK4</a>) and a <a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/res/gresource.xml">resource file</a> for bundling them. A C source file is created from the resource file at build time, compiled and linked statically with the editor DLLs.</p>
<p>And here are a few editor GUI implementations available online:</p>
<ul>
<li><p><a href="https://github.com/GNOME/NetworkManager-openvpn/tree/main/properties">NetworkManager-openvpn</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-openconnect/tree/main/properties">NetworkManager-openconnect</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-fortisslvpn/tree/main/properties">NetworkManager-fortisslvpn</a></p>
</li>
</ul>
<h2>Credentials manager</h2>
<p>One last thing! If you install our plugin right now and compare it to the other plugins, you can notice one weird thing in its behavior. Unlike other plugins that load instantly, our plugin experiences a ~30 seconds delay before its GUI even gets rendered. If you observe the D-Bus logs, you'll notice a stale request to the NetworkManager <a href="https://networkmanager.dev/docs/api/latest/gdbus-org.freedesktop.NetworkManager.SecretAgent.html">secret agent</a>, that times out right in 30 seconds.</p>
<p>That happens because our plugin does not support <code>auth-dialog</code> yet. For some reason, even if plugin backend signals that it doesn't ever need any secrets at all, network manager still requests a secret lookup from the secret agent (e.g. GNOME Keyring or <code>nm-applet</code>) for this plugin. The secret agent, in turn, looks for the auth dialog, can't find it, and then just does nothing instead of reporting back (don't even ask me why at this point), causing request timeout.</p>
<p>Luckily, we can easily solve it by providing the most simple <code>auth-dialog</code> executable ever. Since we don't ever need any secrets, the binary should just exist, accept input arguments, do nothing and then just print two "<code>\n</code>" symbols to STDOUT, that's it.</p>
<p>I assume that in most cases you can just copy-paste my <a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/src/auth_dialog.c">implementation</a> for similar no-secret scenario. You will indeed have to supply it with some logic in case your VPN plugin requires any secrets, but as I mentioned above, this is out of scope of this guide.</p>
<p>Here are a few <code>auth-dialog</code> implementations available online:</p>
<ul>
<li><p><a href="https://github.com/GNOME/NetworkManager-openvpn/tree/main/auth-dialog">NetworkManager-openvpn</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-openconnect/tree/main/auth-dialog">NetworkManager-openconnect</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-fortisslvpn/tree/main/auth-dialog">NetworkManager-fortisslvpn</a></p>
</li>
</ul>
<h2>Putting it all together</h2>
<p>As far as I understood, most plugins use the same file layout and the same build convention. I didn't really like it to be honest, as it relies on some of the tools that I would like to omit and lacks some tools that I would like to include.</p>
<p>With all respect, stacking <code>make</code>, <code>autoconf</code>, shell and python scripts seems a little obscure and too complex to me. That's why I came up with my own simple project layout, relying on <a href="https://mesonbuild.com/">Meson</a> as a modern and flexible build system. Apart from compilation, it handles installation, deployment, code scanning with <a href="https://clang.llvm.org/extra/clang-tidy/">clang-tidy</a> and formatting with <a href="https://clang.llvm.org/docs/ClangFormat.html">clang-format</a>.</p>
<blockquote>
<p>NB! In the beginning I also wanted to use <a href="https://conan.io/">Conan</a> for automatic dependency management, but apparently the default Conan package registry lacks most of the open-source GNOME libraries and also it does not allow depending on two versions of GTK simultaneously, so it's not the best fit here. That's why you should make sure that the required libraries are installed with the default OS package manager. These libraries include: <code>gcc</code> (prefer <code>build-essential</code> if possible), <code>pkg-config</code>, <code>glib-2.0</code>, <code>libnm</code>, <code>gtk+-3.0</code>, <code>gtk4</code>, <code>libsecret-1</code>, <code>clang-tidy</code> and <code>clang-format</code> (both optional).</p>
</blockquote>
<p>You can either review my setup <a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/meson.build">here</a> or use any of the other open-source plugin projects available online:</p>
<ul>
<li><p><a href="https://github.com/GNOME/NetworkManager-openvpn/blob/main/Makefile.am">NetworkManager-openvpn</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-openconnect/blob/main/Makefile.am">NetworkManager-openconnect</a></p>
</li>
<li><p><a href="https://github.com/GNOME/NetworkManager-fortisslvpn/blob/main/Makefile.am">NetworkManager-fortisslvpn</a></p>
</li>
</ul>
<h2>Debugging</h2>
<p>Here are a few practical tips I discovered while debugging my plugin:</p>
<ul>
<li><p><strong>Restart NetworkManager</strong> after every change to the <code>.name</code> file or the frontend DLL: <code>sudo systemctl restart NetworkManager</code>.</p>
</li>
<li><p><strong>Check if NetworkManager sees your plugin</strong>: <code>nmcli connection show</code> should list your VPN type.</p>
</li>
<li><p><strong>Create a test connection</strong>: <code>nmcli connection add type vpn con-name test-vpn vpn-type [PLUGIN_NAME]</code>.</p>
</li>
<li><p><strong>Run the backend manually</strong> for debugging instead of letting D-Bus start it. Kill any existing instance first, then run the executable directly as root. This way you can see all <code>g_debug</code> / <code>g_warning</code> / <code>g_message</code> output in real time.</p>
</li>
<li><p><strong>Monitor D-Bus messages</strong> with <code>dbus-monitor --system</code> to see what NetworkManager sends to your plugin and what your plugin responds with.</p>
</li>
<li><p><strong>Check the system journal</strong> for NetworkManager logs: <code>journalctl -u NetworkManager -f</code>.</p>
</li>
<li><p><strong>Common pitfall</strong>: calling <code>SetConfig</code> from within the <code>Connect</code> handler instead of scheduling it with <code>g_idle_add</code>. This causes a deadlock because D-Bus is not re-entrant.</p>
</li>
</ul>
<h2>Notes</h2>
<ul>
<li><p>The full example plugin source code is available at <a href="https://github.com/pseusys/personal-blog/tree/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin">ExampleVpnPlugin</a>.</p>
</li>
<li><p>The example project ships a standalone demo application rather than a real shared library VPN plugin — the <a href="https://github.com/pseusys/personal-blog/tree/main/sources/misc/netwprk-manager-vpn-plugin/ExampleVpnPlugin/plugin">stub core DLL</a> returns hard-coded values and does not establish an actual VPN tunnel. Replace it with your own implementation.</p>
</li>
<li><p>A <a href="https://github.com/pseusys/personal-blog/blob/main/sources/misc/network-manager-vpn-plugin/Containerfile">Containerfile</a> is provided for verifying a clean build and plugin detection on Fedora (based on the NetworkManager CI image).</p>
</li>
<li><p>The example plugin uses <a href="https://mesonbuild.com/">Meson</a> + <a href="https://ninja-build.org/">Ninja</a> as its build system.</p>
</li>
<li><p>If you find any errors or have suggestions, feel free to open an issue or leave a comment!</p>
</li>
</ul>
]]></content:encoded></item></channel></rss>