# Router provisioning over WireGuard

How you add a MikroTik router and how this server configures it, plus the one-time server setup.

## What you see
1. **Routers → Add a router**: type a name. The server allocates a tunnel address and generates the router's WireGuard key.
2. The page shows **one command** to paste into the router terminal (Winbox → New Terminal). It downloads `billing-bootstrap.rsc` using a **security token** (valid 24 h, max 5 downloads, only a SHA-256 hash is stored) and imports it. The script creates the WireGuard tunnel to the billing server and an API user that can only log in from the server's tunnel address.
3. The page detects the router automatically (tunnel handshake, then API login). The router's real interfaces are read over the API.
4. **Choose what each interface is for**: one WAN, and any of PPPoE, Hotspot, Static IP on the others (PPPoE can use several interfaces; Hotspot and Static use one, so bridge several ports first and pick the bridge). Only interfaces that exist on the router can be chosen; running ports are listed first. Addressing (pool, gateway, DNS, hotspot DNS name) has defaults and is checked for overlaps with each other and with the tunnel pool.
5. **Save & apply**: the router itself fetches its generated config script (`billing-config.rsc`, fresh token, 30 min, over the tunnel) and imports it. The server then checks the objects exist and shows any that are missing. Alternatively **Get a command to run myself**.
6. Plan profiles on that router are re-synced so PPPoE profiles get the right addressing.

The generated script is idempotent (objects named `billing-*` that exist are left alone) and is shown on the page before it is applied. **RouterOS 7.x is required** (WireGuard).

### What the scripts create
| Script | Objects |
|---|---|
| bootstrap | `wg-billing` WireGuard interface and peer (keepalive 25 s), tunnel address, API service restricted to the server, API user `billing` (group `billing`) restricted to the server, an input firewall rule for the API from the server |
| PPPoE | pool `billing-pppoe-pool`, profile `billing-default`, one PPPoE server per chosen interface |
| Hotspot | gateway address, pool, DHCP server + network, hotspot profile and server `billing-hotspot`, walled garden entry for your portal, `hotspot/login.html` that redirects to the portal |
| Static IP | gateway address, firewall rules dropping the `billing-expired` address list (top of the forward chain) |
| all | srcnat masquerade on the WAN |

## One-time server setup
Run on the server that hosts the app (the app reaches routers through the tunnel, so the hub must be on the same host).

1. `sudo ./deploy/wireguard-hub.sh <public-hostname>`: installs WireGuard, creates keys, the base config, and an nftables table that isolates routers from each other and from the server (they may only reach the config port on the tunnel address). It prints the `'wireguard' => [...]` block for `config/config.php`.
2. Open **UDP 51820** to the internet.
3. Serve config scripts on the tunnel address only: `deploy/nginx-tunnel.conf` (nginx) or `deploy/apache-tunnel.conf` (Apache), and keep `/provision/` out of your public vhost's access log (both files show how).
4. Root cron: `* * * * * root php /var/www/billing/bin/wg_sync.php` (adds a peer per router, removes peers of deleted routers, records handshakes). `php bin/wg_sync.php --dry-run` prints what it would write.
5. Run the migrations, then `cron/monitor.php` every minute as before.

### Router must trust your HTTPS certificate
The bootstrap command verifies TLS (`check-certificate=yes-without-crl`). MikroTik has no CA store by default; on the router once:
```
/tool fetch url=https://letsencrypt.org/certs/isrgrootx1.pem
/certificate import file-name=isrgrootx1.pem passphrase=""
```
Using `check-certificate=no` on an untrusted network exposes the token and the API password to a man in the middle.

## Security model
- Tokens: 192-bit random, stored hashed, expiring, use-limited; bootstrap tokens are deleted once the router connects. The config script is only served to the requesting router's own tunnel IP.
- Tunnel: each peer is a single `/32`; the hub firewall drops router-to-router and router-to-server traffic except the config port. The router only accepts the API from the server's tunnel address.
- Staff cannot point a manually-added router (or the GenieACS URL) at the tunnel range.
- The router's WireGuard private key is generated server-side and encrypted at rest (`app_key`); it appears only inside the bootstrap script (over TLS, behind the token).
- Plain API (8728) is used inside the tunnel, which is already encrypted.

## Known limits
- WireGuard routers need RouterOS 7; older routers can still be added manually (public IP or your own VPN).
- A re-run of the config script does not change objects that already exist (change them on the router, or remove the `billing-*` object and apply again).
- Hotspot login uses HTTP PAP (the portal posts the generated credentials to the router's login URL).
- Scripts were written against RouterOS 7 syntax and have not been run on a physical router in this repository's CI. Try on a lab router first.

## Apache instead of nginx
Use `deploy/apache-tunnel.conf`. Checked against Apache 2.4 + PHP-FPM: tunnel listener serves only `/provision/<token>.rsc` (everything else, including direct `rsc.php`, is 404), tokens are single-use, and no token reaches any log.
1. `a2enmod rewrite proxy_fcgi setenvif` (with mod_php, skip `proxy_fcgi` and delete the `SetHandler` block in the file).
2. Copy the file to `sites-available`, set `DocumentRoot`/`<Directory>` to your `public/` folder and the php-fpm socket path, then `a2ensite` and `apachectl configtest`.
3. Start Apache after the tunnel exists (`systemctl edit apache2` → `[Unit] After=wg-quick@wg0.service`), or it cannot bind `10.99.0.1:8081`.
4. Your public HTTPS vhost needs `AllowOverride All` (the bundled `.htaccess` rewrites `/provision/<token>.rsc`) and a `CustomLog` with `env=!nolog` as shown at the bottom of the file. Without its own `CustomLog`, Debian's global `other_vhosts_access.log` records every URL, tokens included.

## Remote access through the hub (WebFig, Winbox, API)
`bin/wg_sync.php` also writes `/etc/wireguard/sb-forward.nft` and loads it as the nftables table `ip sb_fwd`: for each provisioned router, public port `forward_start + id*10` (+0 / +1 / +2) is DNAT-ed to the router's tunnel address on port 80 / 8291 / 8728, and replies are masqueraded so the router sees the hub's tunnel address. Only sources listed in **Routers → Remote access** can use the ports (empty list = anyone). `sb_wg` accepts forwarded (DNAT-ed) traffic towards the tunnel and still drops everything the routers themselves start. The router script adds `input` accept for tcp 80, 8291 and 8728 from the hub's tunnel address. See what would be written: `php bin/wg_sync.php --dry-run`.
