Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Watcher Agent

CI License: AGPL v3+ Go Image

A small, self-contained HTTP agent that runs close to the network (a Docker host on-site, or directly on a MikroTik board) and lets a central Watcher / NMS / CRM reach customer-edge devices it cannot talk to directly.

The agent exposes a thin, token-protected HTTP API for these jobs:

Job Endpoint Protocol used towards the device
Reachability check POST /api/ping ICMP echo (IPv4 & IPv6)
Session teardown POST /api/radius/disconnect RADIUS Disconnect (CoA, RFC 3576 / 5176)
Inventory read POST /api/snmp/read/routeros SNMP v2c
Firewall address lists (debtor blocking) POST /api/routeros/address-list/{sync,add,remove} RouterOS API (api-ssl, api as a fallback)
Access point access lists POST /api/routeros/access-list/remove RouterOS API (api-ssl, api as a fallback)
Auto-provisioning GET /provision/routeros/{type}/{serial} SNMP v2c + call to NMS

It speaks HTTPS (self-signed by default, or Let's Encrypt via ACME), supports the PROXY protocol when placed behind a load balancer, and shuts down gracefully by draining in-flight requests.


How it fits together

        ┌─────────────────────┐     HTTPS + Bearer token      ┌───────────────┐
        │  Watcher / NMS / CRM │ ────────────────────────────▶│ Watcher Agent │
        └─────────────────────┘   /api/ping                   │   (on-site)   │
                  ▲                /api/radius/disconnect       └──────┬────────┘
                  │                /api/snmp/read/routeros              │
                  │                /api/routeros/…                      │ ICMP / SNMP / RADIUS
                  │                                                     │ RouterOS API
                  │                                              ┌──────▼────────┐
                  │  provision script (JSON)                     │ Edge devices  │
                  └──────────────────────────────────────────── │ (RouterOS, …) │
                       /api/agent/provision/routeros.json        └──────┬────────┘
                                                                        │
   RouterOS auto-provisioning flow:                                     │
   device ──GET /provision/routeros/{type}/{serial}──▶ Agent ──SNMP──▶ device
   Agent ──▶ NMS for script ──▶ returns RouterOS script to the device ◀─┘

For provisioning, the RouterOS device itself calls the agent. The agent SNMP-reads the device (using the caller's source IP), verifies the serial number, forwards the inventory to the NMS, and returns the NMS-generated configuration script straight back to the device as a runnable RouterOS script.


Quick start (Docker Compose)

Pull the prebuilt multi-arch image (linux/amd64, linux/arm64) from GHCR:

cp .env.example .env      # edit the values, see Configuration below
docker compose -f compose.production.yaml up -d

compose.production.yaml runs the image :latest, the newest release, and also ships a Watchtower service that auto-updates the agent whenever a new release is published.

To build the image locally instead of pulling it:

docker compose -f compose.production-build.yaml up -d --build

For local development (live go run, source mounted into the container):

docker compose -f compose.dev.yaml up --build

Customizing. The tracked compose.*.yaml files are templates. To adapt one to your environment, copy it to compose.yaml (which is git-ignored) and edit it there — a plain docker compose up -d then picks it up automatically, with no -f flag and without touching the tracked defaults.


Configuration

All configuration is via environment variables (see .env.example). Required variables make the agent refuse to start if unset.

Variable Required Default Description
AGENT_API_ACCESS_JSON ✅¹ (empty) Who may call /api/*: [{"name":"crm","token":"…"},{"name":"nms","token":"…"}]. The name goes into the log of every change. Callers may share a token until each has one of its own; the first with it then names them all. A list that is not one stops the agent from starting.
AGENT_API_TOKEN ✅¹ — A Bearer token for /api/* as before the list, which joins it as the caller default. ¹ One of the two is needed.
AGENT_NMS_BASE_URL ✅ — Base URL of the NMS used for provisioning.
AGENT_NMS_TOKEN ✅ — Bearer token the agent uses when calling the NMS.
AGENT_NMS_VERIFY_TLS true false only against a development NMS with a certificate of its own.
AGENT_ID agent-1 Identifier reported in status / provisioning calls.
AGENT_LISTEN_HTTP 0.0.0.0:80 HTTP listen address (redirects to HTTPS).
AGENT_LISTEN_HTTPS 0.0.0.0:443 HTTPS listen address (the actual API).
AGENT_USE_PROXY_PROTOCOL false Expect a PROXY-protocol header on the HTTPS listener.
AGENT_PROXY_ALLOW_CIDRS (empty) Space-separated CIDRs of the proxy in front of the agent. A PROXY header is used only from these, from anywhere else it is ignored and the connection keeps its real address. Empty: the header is used from anybody and the agent logs a warning at start. Set this with AGENT_USE_PROXY_PROTOCOL.
AGENT_HOSTNAME (empty) If set, obtain a Let's Encrypt cert via ACME for this host; if empty, a self-signed cert is generated.
AGENT_CERT_DIR ./certs Directory where ACME certificates are cached.
AGENT_ROUTEROS_ALLOW_CIDRS 0.0.0.0/0 Space-separated CIDRs allowed to hit /provision/routeros/. Restrict this.
AGENT_ROUTEROS_QUERY_TOKEN (empty) Optional ?token= value additionally required for provisioning.
AGENT_ICMP auto ICMP socket of /api/ping: auto takes an unprivileged one where net.ipv4.ping_group_range allows it (Docker does in every container), a raw one otherwise; unprivileged or raw picks one for good. Another value stops the agent from starting. See ICMP sockets.
AGENT_SNMP_PORT 161 SNMP UDP port.
AGENT_SNMP_TIMEOUT_MS 1500 Per-attempt SNMP timeout.
AGENT_SNMP_RETRIES 1 gosnmp transport-level retries.
AGENT_RADIUS_PORT 1700 Default RADIUS CoA/Disconnect port (overridable per request).
AGENT_RADIUS_TIMEOUT_MS 1500 Per-attempt RADIUS timeout.
AGENT_RADIUS_RETRIES 1 RADIUS retries.
AGENT_DEVICE_TYPES_JSON {} Maps a device-type identifier to its SNMP community (see below).
AGENT_ROUTEROS_API_USERNAME (empty) Account the agent logs in to RouterOS devices with. Empty: the /api/routeros/* endpoints answer 503.
AGENT_ROUTEROS_API_PASSWORD (empty) Its password (not trimmed).
AGENT_ROUTEROS_API_PLAIN_FALLBACK false true allows the unencrypted api (8728) where api-ssl (8729) is refused or the router has no certificate. See RouterOS API transport.
AGENT_ROUTEROS_API_CA_FINGERPRINT (empty) SHA-256 of a CA certificate (hex, colons optional). Set: the router's certificate must be signed by this CA. Empty: encrypted without verification. A value that is not a fingerprint stops the agent from starting.
AGENT_ROUTEROS_API_ALLOW_CIDRS (empty) Space-separated networks the agent may log in to (a bare address is a network of its own). The address is checked after a name is resolved; anything outside gets 403 routeros_target_not_allowed and no connection at all. Empty: any address, and the agent logs a warning at start. A value that is not a network stops the agent from starting. Not the same as AGENT_ROUTEROS_ALLOW_CIDRS, which is who may call provisioning.
AGENT_ROUTEROS_API_TIMEOUT_MS 5000 Timeout for connecting and for each RouterOS API command.

AGENT_DEVICE_TYPES_JSON is consulted during provisioning to pick the SNMP community for a given device type:

{
  "router":          { "community": "public" },
  "bridge":          { "community": "public" },
  "customer-router": { "community": "public" },
  "customer-bridge": { "community": "public" }
}

API reference

All /api/* endpoints require Authorization: Bearer <token> with a token of AGENT_API_ACCESS_JSON or AGENT_API_TOKEN, and return JSON. Errors use { "error": "<code>", "message": "<text>" }.

GET /  ·  health (no auth)

{ "service": "watcher-agent", "status": "ok", "agent_id": "agent-1", "source": "https://github.com/Mapiiik/Watcher-Agent" }

GET /api/status

Returns the version (git describe of the commit the image was built from), uptime and advertised capabilities (the names of the configured device types).

POST /api/ping

Pings over the ICMP socket AGENT_ICMP picks, see ICMP sockets.

// request
{ "host": "10.0.0.1", "count": 3, "timeout_ms": 800 }
// response
{
  "reachable": true, "target_ip": "10.0.0.1",
  "sent": 3, "received": 3, "lost": 0, "loss_pct": 0,
  "rtt_min_ms": 1.2, "rtt_avg_ms": 1.8, "rtt_max_ms": 2.5
}

host may be a hostname; if it resolves to both families an IPv6 address is preferred. count may be 100 at most, timeout_ms 100 at least and the two times each other 120000 at most; otherwise the answer is a 400. A caller that closes the connection gets no more pings sent for it. A request the agent could not send is not in sent; with none sent the answer is a 500 with ping_failed, which says nothing about the host.

POST /api/radius/disconnect

Sends a RADIUS Disconnect-Request to a NAS. nas_ip and secret are required; the remaining attributes refine which session is torn down.

// request
{
  "nas_ip": "10.0.0.1", "port": 1700, "secret": "s3cr3t",
  "username": "user@isp", "acct_session_id": "81a0f3c2",
  "framed_ip": "100.64.0.5", "timeout_ms": 1500
}
// response
{ "success": true, "result": "Disconnect-ACK", "error_causes": [] }

result is one of Disconnect-ACK, Disconnect-NAK, Timeout after N attempts, or Exception. Any RFC 5176 Error-Cause values are returned in error_causes.

POST /api/snmp/read/routeros

Reads device, interface and IP-address inventory from a RouterOS device over SNMP v2c.

// request
{ "host": "10.99.196.251", "community": "public" }
// response (abridged)
{
  "device": {
    "serial_number": "ABC123", "ip_address": "10.99.196.251",
    "name": "edge-1", "board_name": "RB5009", "software_version": "7.x", ...
  },
  "interfaces": [ { "interface_index": 1, "name": "ether1", "mac_address": "…", "ssid": null, … } ],
  "ip_addresses": [ { "interface_index": 8, "ip_address": "10.99.196.251/29", "name": "10.99.196.251" } ]
}

A read gives up after 110 s, and on a table of over 50 000 values, far above what a real device has.

RouterOS note: the IP-address inventory comes from the standard ipAddrTable (.1.3.6.1.2.1.4.20). Some RouterOS versions leave this table empty until the IP address is re-applied on the device, which surfaces here as SNMP walk failed … for .1.3.6.1.2.1.4.20.1.1: empty response. RouterOS does not implement the newer ipAddressTable (.4.34), so there is no fallback.

POST /api/routeros/address-list/sync · add · remove

Changes a firewall address list on a RouterOS device, both /ip and /ipv6; the agent picks the family from each address. Addresses are compared as the firewall reads them, so 192.0.2.1 and 192.0.2.1/32 are one entry and a network is masked. Only static entries are touched: a dynamic one was put there by a firewall rule with a timeout.

  • sync makes the list hold exactly entries: missing ones are added, a different comment or a disabled entry is corrected, everything else on the list is removed.
  • add writes entries and leaves the rest of the list alone.
  • remove takes addresses off the list.

Removals always come last, so a command failing half way leaves the list blocking more rather than fewer. entries (or addresses) must be present; an empty array is fine and with sync empties the list.

// request (sync, add)
{
  "host": "192.0.2.1", "list": "debtors",
  "entries": [
    { "address": "198.51.100.7", "comment": "1234 - Jan Novak" },
    { "address": "2001:db8:1::/48", "comment": "1235 - Firma s.r.o." }
  ]
}
// request (remove)
{ "host": "192.0.2.1", "list": "debtors", "addresses": ["198.51.100.7"] }
// response
{
  "host": "192.0.2.1", "transport": "api-ssl",
  "added":   [ { "address": "198.51.100.7", "family": "ipv4", "comment": "1234 - Jan Novak" } ],
  "updated": [],
  "removed": [ { "address": "203.0.113.9", "family": "ipv4", "comment": "1200 - Paid Meanwhile" } ],
  "unchanged": 41
}

POST /api/routeros/access-list/remove

Removes a station from the access lists of an access point, so that it has to be accepted again. Tries /interface/wireless, /interface/wifi and /interface/wifiwave2 (the name before RouterOS 7.13) and passes over those the device does not have.

// request
{ "host": "10.1.2.3", "mac_address": "AA:BB:CC:DD:EE:FF" }
// response
{
  "host": "10.1.2.3", "transport": "api",
  "removed": [ { "menu": "/interface/wifi/access-list", "interface": "wifi1", "mac_address": "AA:BB:CC:DD:EE:FF" } ]
}

Errors of the RouterOS endpoints:

Status error When
400 bad_request Unreadable JSON, a missing parameter, an address or MAC that is not one.
503 not_configured AGENT_ROUTEROS_API_USERNAME is empty.
403 routeros_target_not_allowed The host is outside AGENT_ROUTEROS_API_ALLOW_CIDRS; the agent did not connect.
502 routeros_unreachable No connection by any allowed way.
502 routeros_login_failed The device refused the login.
502 routeros_certificate_invalid A CA fingerprint is set and the device's certificate does not pass it.
502 routeros_command_failed The device refused a command; the message names it and what was done before.

RouterOS API transport

The agent connects to api-ssl (8729) first. Without a certificate RouterOS offers only anonymous Diffie-Hellman there, which Go does not implement, so a router needs a certificate for it; a self-signed one made on the router is enough.

The unencrypted api (8728) is tried only with AGENT_ROUTEROS_API_PLAIN_FALLBACK=true, and only when the router does no TLS at all: api-ssl refuses the connection, or answers the handshake with a handshake_failure alert (no certificate). A timeout, a broken handshake, a certificate failing the CA or a login refused over TLS are errors and never lead to the plain api. Every plain connection is logged with the reason:

RouterOS API 192.0.2.1: plain api (no certificate for api-ssl)

Without AGENT_ROUTEROS_API_CA_FINGERPRINT the certificate is not verified: nobody on the way reads the password, but whoever answers on the address does, encrypted or not. A caller with the API token could name a server of its own, so keep AGENT_ROUTEROS_API_ALLOW_CIDRS to the networks of the devices. With a fingerprint, the CA has to be in the chain the router sends and has to have signed the router's certificate. Neither the router's address nor its name is checked, as both change when devices are replaced or renumbered.

GET /provision/routeros/{deviceType}/{serial}

Called by the RouterOS device itself during auto-provisioning. Guarded by AGENT_ROUTEROS_ALLOW_CIDRS (source-IP allowlist) and, optionally, a ?token= matching AGENT_ROUTEROS_QUERY_TOKEN. The agent:

  1. SNMP-reads the serial from the caller's IP and checks it matches {serial},
  2. performs a full SNMP read,
  3. POSTs the inventory to …/api/agent/provision/routeros.json on the NMS,
  4. returns the NMS's RouterOS script verbatim (Content-Type: text/plain).

On any failure the response is a RouterOS-runnable error line so the device logs it:

:log error "Watcher Agent: SNMP read failed: …"

Deployment notes

  • Logs. Every change and every refused request is one line on stderr with the caller's address (the one from the PROXY header behind a proxy): RADIUS disconnects, address and access list changes with the addresses changed, provisioning, and requests refused for a token or an address, for example INFO RouterOS address list changed client=192.0.2.1 op=sync host=10.1.2.3 list=debtors transport=api-ssl added=… removed=…. RADIUS secrets, tokens and the comments of address lists never go in.
  • Capabilities. Binding to ports 80/443 needs NET_BIND_SERVICE. /api/ping needs NET_RAW only for a raw ICMP socket, see ICMP sockets. Both are granted in the provided compose files via cap_add.

ICMP sockets

/api/ping keeps one ICMP socket for IPv4 and one for IPv6, opened at start; the log says which kind each is (ICMP IPv4: pinging over an unprivileged socket). One that cannot be opened is logged and tried again with the next ping.

  • Unprivileged (SOCK_DGRAM) needs only the group of the process in net.ipv4.ping_group_range, which covers IPv6 too. Docker sets it to every group in a container. The kernel gives the requests the socket's echo ID and hands the socket only its own replies.
  • Raw needs NET_RAW and would get every ICMP message of the machine; a filter in the kernel lets only echo replies through, and every request has an echo ID of its own.

At most 512 requests per socket wait for a reply at once, the next ones wait for their turn, which bounds what the socket's buffer has to hold. Each socket asks for a 4 MiB buffer, which the kernel caps at net.core.rmem_max. The package src/infra/icmpsocket is the same byte for byte in Watcher Pinger.

  • TLS. With AGENT_HOSTNAME unset the agent serves a freshly generated self-signed certificate (30-day validity, regenerated on each restart). Set AGENT_HOSTNAME to a public name and persist AGENT_CERT_DIR to use ACME / Let's Encrypt instead.
  • Timeouts. A client gets 30 s for the TLS handshake with the request headers and for the whole request, an idle connection is closed after 120 s, and an answer has to be out within 150 s, which is longer than the longest request takes.
  • Graceful shutdown. On SIGINT/SIGTERM the agent stops accepting new requests, waits up to 50 s for in-flight ones to finish, then shuts down. Keep stop_grace_period above that (the compose files use 60 s).
  • Running on a MikroTik board. RouterOS 7.x can run the agent as a native container. See docs/routeros-container.md for a starting point (note: ICMP ping may be unavailable inside a RouterOS container).

Development

go vet ./...
go test ./...
golangci-lint run
docker compose -f compose.dev.yaml up --build   # live reload via `go run`

CI (GitHub Actions) runs go mod tidy verification, go vet, golangci-lint and tests on every push/PR, then builds and pushes the multi-arch image to GHCR: main from main, and from a tag, a bare version such as 1.0.0, the version, with its major number and latest while it is the newest release. A nightly run rebuilds main and the newest release when a new Go patch release or Alpine image is out. Go cross-compiles and nothing runs on the target platform, so the arm64 image needs no emulation.

Project layout

src/
  main/          process wiring: config, TLS, auth, graceful drain, HTTP servers
  httpapi/       HTTP handlers (root, status, ping, radius, snmp, routeros, provision)
  httphelpers/   JSON and RouterOS error responses
  domain/
    snmp/        RouterOS SNMP read (device, interfaces, IP addresses, wireless)
    radius/      RADIUS Disconnect (RFC 3576 / 5176)
    routeros/    RouterOS API: address lists, access lists, api-ssl with the plain api fallback
  infra/
    icmpsocket/  ICMP sockets for IPv4 and IPv6, unprivileged or raw (the same in Watcher Pinger)
  integration/
    nms/         client for the central NMS provisioning API
  testutil/
    snmpagent/   minimal SNMP v2c agent the tests read from
    routerosapi/ minimal RouterOS API server (plain and TLS) the tests talk to

License

Copyright (C) 2026 Martin Patočka

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU AGPL v3 for more details.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages