WireGuard tunnel, Add peer tunnel Import peer tunnel overwriting peers

Issue: Import peer tunnel overwrites an existing tunnel when wg numbers have a gap

Body:

Import peer tunnel picks the new interface by counting current WireGuard interfaces. It never checks whether that wgN section already exists, so a gap in the numbering makes it write over the last tunnel.

import_configuration() in packages/ns-api/files/ns.wireguard calls get_instance_defaults(). That helper starts at 1 and adds 1 for every network section with proto wireguard, then uses wg plus that total:

next_instance = 1
for entry in u.get('network'):
    if u.get('network', entry, 'proto', default='') == 'wireguard':
        next_instance += 1
interface = f'wg{next_instance}'

import_configuration() then does e_uci.set('network', defaults['instance'], 'interface') on that name. There is no test that the section is free.

__next_instance() already walks wg1 … wg99 and returns the first name whose proto is unset. Import does not use it.

The UI label (ns_name) is not involved. Deleting a peer tunnel is. Delete removes that interface and does not renumber the ones left behind.

Steps

  1. Peer tunnels on wg1 and wg3 (wg2 removed earlier). Both connected.
  2. Peer tunnel → Import peer tunnel, and import a new config.

Expected

A new interface on the first free name (wg2 or wg4). wg1 and wg3 stay as they are.

Actual

Two remaining interfaces count up to 3, so Import writes wg3 and replaces the existing tunnel (private key, address, and name).

Fix

Allocate the name by checking for an existing config and incrementing until the name is free, the same way __next_instance() already does. add_tunnel() uses get_instance_defaults() too, so the Add button has the same hole.

Seen on NethSecurity 8.8.0.

Issue opened: WireGuard: importing a peer tunnel overwrites an existing tunnel · Issue #1915 · NethServer/nethsecurity · GitHub

Thanks,

Let’s just say it made my day very interesting when adding a backup link took out the main office wireguard channel. :rofl::rofl::rofl: