initial import: netbird open-wifi enforcement (user service, trusted list gui, panel indicator)

This commit is contained in:
Bastian Mäuser committed 2026-11-09 00:13:13 +01:00
commit 57b77f5423
9 files changed
+404

No files matched your search

+1
View File
@@ -0,0 +1 @@
*.shell-extension.zip
+16
View File
@@ -0,0 +1,16 @@
UUID = netbird-hooks@netz.org
BUNDLE = netbird-hooks.shell-extension.zip
all: $(BUNDLE)
$(BUNDLE): extension.js metadata.json prefs.js netbird-policy.sh schemas/org.gnome.shell.extensions.netbird-hooks.gschema.xml
glib-compile-schemas schemas
zip $@ extension.js metadata.json prefs.js netbird-policy.sh schemas/gschemas.compiled schemas/org.gnome.shell.extensions.netbird-hooks.gschema.xml
install: $(BUNDLE)
gnome-extensions install --force $(BUNDLE)
clean:
rm -f $(BUNDLE)
.PHONY: all install clean
+57
View File
@@ -0,0 +1,57 @@
# netbird-hooks
GNOME Shell extension (GNOME 50): enforces netbird connectivity while you are
on an open (unencrypted) wifi, with a configurable trusted-networks
exemption list. Trusted or WPA-secured networks are never touched; netbird is
never brought down.
## How it works
- A tiny systemd **user** service (`netbird-hooks.service`, written and
started by the extension) watches NetworkManager via `nmcli monitor` and
runs the policy check on every connection change. No root anywhere.
- On each event the policy re-reads its config from gsettings
(`org.gnome.shell.extensions.netbird-hooks`), so preference changes apply
on the next network event without restarting anything.
- Policy: enforcement enabled AND the connected device is wifi AND the wifi
is open AND the SSID is not on the trusted list AND netbird is not already
connected -> `netbird up` (netbird's own default/auto exit selection).
- Every trigger is logged: `journalctl -t netbird-hooks`.
- A panel indicator shows the live netbird state (green = connected,
red = down), refreshed on network events and every 15s.
## The GUI
Extensions app -> "NetBird Hooks" -> gear:
- **Enforce netbird on open wifi** — master switch
- **Show panel indicator** — toggle the top-bar icon
- **Trusted networks** — SSIDs where netbird is never enforced; add by
typing or via "Add current network", remove per row
Equivalent CLI:
gsettings set org.gnome.shell.extensions.netbird-hooks enforce false
gsettings set org.gnome.shell.extensions.netbird-hooks trusted-ssids "['my-cafe']"
## Install
make install
then log out and back in (the extension + indicator load on the next
session; the user service can also be started standalone, see below), and
enable:
gnome-extensions enable netbird-hooks@netz.org
Manual service start without the extension (the unit is written by the
extension's enable(); a static copy works too):
systemctl --user enable --now netbird-hooks.service
## Files
- `netbird-policy.sh` — the watcher loop; `netbird-policy.sh once` runs a
single policy check (handy for testing)
- `schemas/` — gsettings schema (compiled by `make`)
- `extension.js` / `prefs.js` — shell integration + preferences UI
+131
View File
@@ -0,0 +1,131 @@
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import GObject from 'gi://GObject';
import NM from 'gi://NM';
import St from 'gi://St';
import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js';
import * as Main from 'resource:///org/gnome/shell/ui/main.js';
import * as PanelMenu from 'resource:///org/gnome/shell/ui/panelMenu.js';
const UNIT = 'netbird-hooks.service';
const GREEN = '#A3BE8C';
const RED = '#BF616A';
const Indicator = GObject.registerClass(
class Indicator extends PanelMenu.Button {
_init(settings) {
super._init(0.0, 'NetBird Hooks', true);
this._settings = settings;
this._icon = new St.Icon({icon_name: 'network-vpn-symbolic',
style_class: 'system-status-icon', style: `color: ${RED};`});
this.add_child(this._icon);
this._client = NM.Client.new(null);
this._client.connectObject(
'notify::active-connections', () => this._refresh(),
'notify::connectivity', () => this._refresh(),
this);
this._timer = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 15,
() => {
this._refresh();
return GLib.SOURCE_CONTINUE;
});
this._refresh();
}
_refresh() {
if (this._pending)
return;
this._pending = true;
try {
const proc = Gio.Subprocess.new(['netbird', 'status'],
Gio.SubprocessFlags.STDOUT_PIPE |
Gio.SubprocessFlags.STDERR_SILENCE);
proc.communicate_utf8_async(null, null, (p, res) => {
this._pending = false;
let connected = false;
try {
const [, out] = p.communicate_utf8_finish(res);
connected = p.get_exit_status() === 0 &&
/Management: Connected/i.test(out ?? '');
} catch {
connected = false;
}
this._setConnected(connected);
});
} catch {
this._pending = false;
this._setConnected(false);
}
}
_setConnected(connected) {
this.visible = this._settings.get_boolean('show-indicator');
this._icon.style = `color: ${connected ? GREEN : RED};`;
}
destroy() {
if (this._timer) {
GLib.source_remove(this._timer);
this._timer = null;
}
this._client.disconnectObject(this);
super.destroy();
}
});
export default class NetbirdHooksExtension extends Extension {
enable() {
this._settings = this.getSettings();
this._unitPath = GLib.build_filenamev([GLib.get_user_config_dir(),
'systemd', 'user', UNIT]);
this._writeUnit();
this._systemctl(['daemon-reload']);
this._systemctl(['enable', '--now', UNIT]);
this._indicator = new Indicator(this._settings);
Main.panel.addToStatusArea(this.uuid, this._indicator);
}
disable() {
this._indicator.destroy();
this._indicator = null;
this._systemctl(['disable', '--now', UNIT]);
try {
Gio.File.new_for_path(this._unitPath).delete(null);
} catch {
}
this._systemctl(['daemon-reload']);
this._settings = null;
}
_writeUnit() {
GLib.mkdir_with_parents(GLib.path_get_dirname(this._unitPath), 0o755);
const contents = [
'[Unit]',
'Description=NetBird open-wifi enforcement watcher',
'After=network-online.target',
'',
'[Service]',
'Type=simple',
`ExecStart=/bin/sh ${this.path}/netbird-policy.sh`,
'Restart=on-failure',
'RestartSec=5',
'',
'[Install]',
'WantedBy=default.target',
'',
].join('\n');
GLib.file_set_contents(this._unitPath, contents);
}
_systemctl(args) {
try {
const proc = Gio.Subprocess.new(['systemctl', '--user', ...args],
Gio.SubprocessFlags.NONE);
proc.wait_check(null);
} catch (e) {
logError(e, 'netbird-hooks systemctl');
}
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"uuid": "netbird-hooks@netz.org",
"name": "NetBird Hooks",
"description": "Enforces netbird connectivity on open (unencrypted) wifi, with a configurable trusted-networks exemption list. Ships a user service watching NetworkManager and a panel indicator.",
"shell-version": ["50"],
"settings-schema": "org.gnome.shell.extensions.netbird-hooks"
}
+56
View File
@@ -0,0 +1,56 @@
#!/bin/sh
# netbird-hooks: enforce netbird connectivity on open (unencrypted) wifi,
# except for SSIDs on the trusted list. Runs as a systemd user service and
# reacts to NetworkManager connection changes. Config is read live from
# gsettings org.gnome.shell.extensions.netbird-hooks on every event, so
# preference changes apply immediately.
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export PATH
GSETTINGS_SCHEMA_DIR="$(cd "$(dirname "$0")" && pwd)/schemas"
export GSETTINGS_SCHEMA_DIR
SCHEMA=org.gnome.shell.extensions.netbird-hooks
log() { logger -t netbird-hooks "$*"; }
is_trusted() {
gsettings get $SCHEMA trusted-ssids 2>/dev/null | sed "s/[][']//g" \
| tr ',' '\n' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' \
| grep -Fxq -- "$1"
}
check() {
[ "$(gsettings get $SCHEMA enforce 2>/dev/null)" = 'true' ] || return 0
# connected wifi device; ethernet and wwan are never enforced
dev=$(nmcli -t -f DEVICE,TYPE,STATE device 2>/dev/null \
| awk -F: '$2 == "wifi" && $3 == "connected" {print $1; exit}')
[ -n "$dev" ] || return 0
# only unencrypted wifis
sec=$(nmcli -g active,security dev wifi 2>/dev/null \
| awk -F: '$1 == "yes" {print $2; exit}')
[ -z "$sec" ] || return 0
command -v iw >/dev/null 2>&1 || return 0
ssid=$(iw dev "$dev" link 2>/dev/null | sed -n 's/^[[:space:]]*SSID: //p')
[ -n "$ssid" ] || return 0
if is_trusted "$ssid"; then
return 0
fi
# already connected?
netbird status 2>/dev/null | grep -qi 'Management: Connected' && return 0
log "open wifi '$ssid' (dev $dev) not trusted, connecting netbird"
netbird up
}
case "$1" in
once) check; exit 0 ;;
esac
nmcli monitor 2>/dev/null | while read -r _; do
sleep 1
check
done
+116
View File
@@ -0,0 +1,116 @@
import Adw from 'gi://Adw';
import Gio from 'gi://Gio';
import Gtk from 'gi://Gtk';
import {ExtensionPreferences, gettext as _} from
'resource:///org/gnome/Shell/Extensions/js/extensions/prefs.js';
export default class NetbirdHooksPreferences extends ExtensionPreferences {
fillPreferencesWindow(window) {
this._rows = [];
const settings = this.getSettings();
const page = new Adw.PreferencesPage();
const gen = new Adw.PreferencesGroup({title: _('Enforcement')});
const enforceRow = new Adw.SwitchRow({
title: _('Enforce netbird on open wifi'),
subtitle: _('Connect netbird (with its default exit selection) whenever the active wifi is unencrypted'),
});
settings.bind('enforce', enforceRow, 'active',
Gio.SettingsBindFlags.DEFAULT);
gen.add(enforceRow);
const indRow = new Adw.SwitchRow({
title: _('Show panel indicator'),
subtitle: _('Top-bar icon: green = netbird connected, red = down'),
});
settings.bind('show-indicator', indRow, 'active',
Gio.SettingsBindFlags.DEFAULT);
gen.add(indRow);
page.add(gen);
const tg = new Adw.PreferencesGroup({
title: _('Trusted networks'),
description: _('Netbird is never enforced on these SSIDs'),
});
this._group = tg;
this._rebuildSsidRows(settings);
settings.connect('changed::trusted-ssids',
() => this._rebuildSsidRows(settings));
const box = new Gtk.Box({
orientation: Gtk.Orientation.HORIZONTAL,
spacing: 6,
margin_top: 6,
});
const entry = new Gtk.Entry({
hexpand: true,
placeholder_text: _('SSID'),
});
entry.connect('activate', () => this._addSsid(entry.get_text(), settings, entry));
box.append(entry);
const addBtn = new Gtk.Button({label: _('Add')});
addBtn.connect('clicked', () => this._addSsid(entry.get_text(), settings, entry));
box.append(addBtn);
const curBtn = new Gtk.Button({label: _('Add current network')});
curBtn.connect('clicked', () => this._addCurrent(settings));
box.append(curBtn);
tg.add(box);
page.add(tg);
window.add(page);
}
_rebuildSsidRows(settings) {
for (const row of this._rows)
this._group.remove(row);
this._rows = [];
for (const ssid of settings.get_strv('trusted-ssids')) {
const row = new Adw.ActionRow({title: ssid});
const btn = new Gtk.Button({
icon_name: 'user-trash-symbolic',
valign: Gtk.Align.CENTER,
});
btn.connect('clicked', () => {
settings.set_strv('trusted-ssids',
settings.get_strv('trusted-ssids').filter(x => x !== ssid));
});
row.add_suffix(btn);
this._group.add(row);
this._rows.push(row);
}
}
_addSsid(text, settings, entry) {
const ssid = (text ?? '').trim();
if (!ssid)
return;
const list = settings.get_strv('trusted-ssids');
if (!list.includes(ssid)) {
list.push(ssid);
settings.set_strv('trusted-ssids', list);
}
if (entry)
entry.set_text('');
}
_addCurrent(settings) {
const cmd = ['sh', '-c',
'd=$(nmcli -t -f DEVICE,TYPE,STATE device 2>/dev/null | ' +
"awk -F: '$2 == \"wifi\" && $3 == \"connected\" {print $1; exit}'); " +
'[ -n "$d" ] && iw dev "$d" link 2>/dev/null | ' +
"sed -n 's/^[[:space:]]*SSID: //p'"];
try {
const proc = Gio.Subprocess.new(cmd,
Gio.SubprocessFlags.STDOUT_PIPE);
proc.communicate_utf8_async(null, null, (p, res) => {
try {
const [, out] = p.communicate_utf8_finish(res);
this._addSsid((out ?? '').trim(), settings, null);
} catch {
}
});
} catch {
}
}
}
Binary file not shown.
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<schemalist>
<schema id="org.gnome.shell.extensions.netbird-hooks" path="/org/gnome/shell/extensions/netbird-hooks/">
<key name="enforce" type="b">
<default>true</default>
<summary>Enforce netbird on open wifi</summary>
<description>Connect netbird (with its default exit selection) whenever the active wifi is unencrypted and not on the trusted list.</description>
</key>
<key name="trusted-ssids" type="as">
<default>[]</default>
<summary>Trusted networks</summary>
<description>SSIDs on which netbird is never enforced, even when open.</description>
</key>
<key name="show-indicator" type="b">
<default>true</default>
<summary>Show panel indicator</summary>
<description>Show a panel icon reflecting the netbird connection state.</description>
</key>
</schema>
</schemalist>