diff --git a/CHANGELOG.md b/CHANGELOG.md index fa679ee..d34691f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,8 @@ publish a tag that has no section here. switches marked; NetBox cables that disagree with LLDP are shown. - NetBox's web UI through Rollcall at its `BASE_PATH` (admins only), and links to NetBox from the web UI (sidebar, sites, rooms, racks, switches, machine devices); `ipam.ui_url` for direct links. + With `ipam.ui_login_secret_file` the admin certificate signs in to NetBox too (NetBox's remote + user header, guarded by a shared secret the web server in front of NetBox checks). - Sites page: sites on an OpenStreetMap map (Leaflet shipped in the binary), a site's rooms, and a room's floor plan with racks on 600 mm tiles coloured by their machines; a rack opens its front. Racks are placed by dragging and rotated in an edit mode; unplaced ones are laid out diff --git a/README.md b/README.md index 47e317a..0398c5f 100644 --- a/README.md +++ b/README.md @@ -892,6 +892,36 @@ BASE_PATH = 'netbox/' CSRF_TRUSTED_ORIGINS = ['https://rollcall.example'] # where browsers post from ``` +**Signing in with the admin certificate.** With `"ui_login_secret_file"` in the +`ipam` block, the proxy tells NetBox who the admin is: `X-Rollcall-User` (the +certificate's admin name) with the shared secret in `X-Rollcall-Proxy-Secret`. +NetBox takes the user from that header and creates it on first use: + +```python +REMOTE_AUTH_ENABLED = True +REMOTE_AUTH_BACKEND = 'netbox.authentication.RemoteUserBackend' +REMOTE_AUTH_HEADER = 'HTTP_X_ROLLCALL_USER' +REMOTE_AUTH_AUTO_CREATE_USER = True +REMOTE_AUTH_DEFAULT_GROUPS = ['rollcall-admins'] # give this group the permissions admins should have +``` + +The web server in front of NetBox must drop `X-Rollcall-User` from every +request that does not come from Rollcall with the secret, or anyone who reaches +NetBox directly could claim a user. With Caddy: + +``` +@notrollcall not { + remote_ip 10.0.0.5 # the region + header X-Rollcall-Proxy-Secret "" +} +request_header @notrollcall -X-Rollcall-User +request_header -X-Rollcall-Proxy-Secret +``` + +Rollcall drops both headers when a browser sends them. An admin with a token +instead of a certificate signs in to NetBox by hand. `lab/netbox/install.sh` +sets all of this up for the lab NetBox. + The web UI then links to NetBox: the sidebar, a site, room and rack on the Sites pages, a switch, and a machine's device. `ipam.ui_url` points those links elsewhere (NetBox reached directly) when that is preferred; a NetBox at the root diff --git a/cmd/rollcall/ipam.go b/cmd/rollcall/ipam.go index 9ecebe5..00794fc 100644 --- a/cmd/rollcall/ipam.go +++ b/cmd/rollcall/ipam.go @@ -37,19 +37,20 @@ import ( ) type IPAMConfig struct { - Provider string `json:"provider"` // "" = built-in only | netbox | infoblox - URL string `json:"url"` // https://netbox.example; with NetBox's BASE_PATH (…/netbox/) its UI is served here too (nbproxy.go) - UIURL string `json:"ui_url"` // where "open in NetBox" links go when not through Rollcall - TokenFile string `json:"token_file"` // API token (NetBox v2 "nbt_..." or v1) - User string `json:"user"` // Infoblox WAPI user - PasswordFile string `json:"password_file"` // Infoblox WAPI password - NetworkView string `json:"network_view"` // Infoblox, default "default" - DNSView string `json:"dns_view"` // Infoblox host records' DNS view, default "default"; "-" = IPAM only - CAFile string `json:"ca_file"` // CA that signed the server certificate ("" = system roots) - DNSZone string `json:"dns_zone"` // dns_name = . unless the subnet has a domain - Tag string `json:"tag"` // ownership tag, default "rollcall" - MachineField string `json:"machine_field"` // custom field holding the machine ID, default "rollcall_machine" - SyncInterval string `json:"sync_interval"` // reconcile period, default 5m + Provider string `json:"provider"` // "" = built-in only | netbox | infoblox + URL string `json:"url"` // https://netbox.example; with NetBox's BASE_PATH (…/netbox/) its UI is served here too (nbproxy.go) + UIURL string `json:"ui_url"` // where "open in NetBox" links go when not through Rollcall + UILoginFile string `json:"ui_login_secret_file"` // shared with NetBox's front: the admin certificate signs in to NetBox (nbproxy.go) + TokenFile string `json:"token_file"` // API token (NetBox v2 "nbt_..." or v1) + User string `json:"user"` // Infoblox WAPI user + PasswordFile string `json:"password_file"` // Infoblox WAPI password + NetworkView string `json:"network_view"` // Infoblox, default "default" + DNSView string `json:"dns_view"` // Infoblox host records' DNS view, default "default"; "-" = IPAM only + CAFile string `json:"ca_file"` // CA that signed the server certificate ("" = system roots) + DNSZone string `json:"dns_zone"` // dns_name = . unless the subnet has a domain + Tag string `json:"tag"` // ownership tag, default "rollcall" + MachineField string `json:"machine_field"` // custom field holding the machine ID, default "rollcall_machine" + SyncInterval string `json:"sync_interval"` // reconcile period, default 5m // DeviceSync mirrors machines as NetBox devices (nbdevices.go); nil = off DeviceSync *DeviceSyncConfig `json:"device_sync,omitempty"` } diff --git a/cmd/rollcall/nbproxy.go b/cmd/rollcall/nbproxy.go index 41614eb..254b7b5 100644 --- a/cmd/rollcall/nbproxy.go +++ b/cmd/rollcall/nbproxy.go @@ -10,11 +10,22 @@ package main // // ui_url, when set, is where links to NetBox point instead (NetBox reached // directly); the proxy stays. +// +// Signing in with the admin certificate: with ui_login_secret_file, the +// proxy tells NetBox who the admin is (X-Rollcall-User: the certificate's +// admin name) together with the shared secret (X-Rollcall-Proxy-Secret). +// NetBox takes the user from that header (REMOTE_AUTH_HEADER), and the web +// server in front of NetBox must drop it from any request without the +// secret, or anyone reaching NetBox directly could claim a user. Both +// headers coming from the browser are always dropped here. An admin with a +// token instead of a certificate signs in to NetBox by hand. import ( + "fmt" "net/http" "net/http/httputil" "net/url" + "os" "strings" ) @@ -42,16 +53,32 @@ func (a *App) netboxUILink() string { return a.netboxUIPath() } -func (a *App) netboxProxy() http.Handler { +func (a *App) netboxProxy() (http.Handler, error) { nb := a.ipam.(*netBox) target, _ := url.Parse(nb.base) origin := target.Scheme + "://" + target.Host + secret := "" + if f := a.cfg.IPAM.UILoginFile; f != "" { + b, err := os.ReadFile(f) + if err != nil { + return nil, fmt.Errorf("ipam ui_login_secret_file: %w", err) + } + if secret = strings.TrimSpace(string(b)); len(secret) < 16 { + return nil, fmt.Errorf("ipam ui_login_secret_file: under 16 characters") + } + } return &httputil.ReverseProxy{ Transport: nb.client.Transport, Rewrite: func(pr *httputil.ProxyRequest) { pr.Out.URL.Scheme, pr.Out.URL.Host = target.Scheme, target.Host pr.Out.Host = target.Host pr.Out.Header.Del("Authorization") // Rollcall's credentials are not NetBox's + pr.Out.Header.Del("X-Rollcall-User") + pr.Out.Header.Del("X-Rollcall-Proxy-Secret") + if name := a.peerAdmin(pr.In); name != "" && secret != "" { + pr.Out.Header.Set("X-Rollcall-User", name) + pr.Out.Header.Set("X-Rollcall-Proxy-Secret", secret) + } pr.SetXForwarded() }, ModifyResponse: func(resp *http.Response) error { @@ -60,5 +87,5 @@ func (a *App) netboxProxy() http.Handler { } return nil }, - } + }, nil } diff --git a/cmd/rollcall/nbproxy_test.go b/cmd/rollcall/nbproxy_test.go index 84f713d..f2049cc 100644 --- a/cmd/rollcall/nbproxy_test.go +++ b/cmd/rollcall/nbproxy_test.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "os" "testing" ) @@ -32,10 +33,15 @@ func TestNetBoxProxy(t *testing.T) { })) defer up.Close() a := &App{cfg: &Config{IPAM: IPAMConfig{URL: up.URL + "/netbox/"}}, ipam: &netBox{base: up.URL + "/netbox", client: up.Client()}} - h := a.netboxProxy() + h, err := a.netboxProxy() + if err != nil { + t.Fatal(err) + } req := httptest.NewRequest("GET", "https://rollcall.example/netbox/", nil) req.Header.Set("Authorization", "Bearer rollcall-admin") + req.Header.Set("X-Rollcall-User", "admin") // a browser claiming a NetBox user + req.Header.Set("X-Rollcall-Proxy-Secret", "guessed") // and the secret rec := httptest.NewRecorder() h.ServeHTTP(rec, req) if rec.Code != http.StatusFound || rec.Header().Get("Location") != "/netbox/login/?next=/netbox/" { @@ -44,6 +50,9 @@ func TestNetBoxProxy(t *testing.T) { if seen.Header.Get("Authorization") != "" { t.Fatal("Rollcall's credentials went to NetBox") } + if seen.Header.Get("X-Rollcall-User") != "" || seen.Header.Get("X-Rollcall-Proxy-Secret") != "" { + t.Fatal("the browser's user header went to NetBox") + } rec = httptest.NewRecorder() h.ServeHTTP(rec, httptest.NewRequest("GET", "https://rollcall.example/netbox/dcim/sites/?q=lab", nil)) if rec.Body.String() != "netbox page" || seen.URL.RequestURI() != "/netbox/dcim/sites/?q=lab" || seen.Header.Get("X-Forwarded-Host") != "rollcall.example" { @@ -84,3 +93,29 @@ func TestNetBoxProxyRoutes(t *testing.T) { } } } + +// with the shared secret set, a request without an admin certificate signs no one in +func TestNetBoxProxyLoginNeedsCertificate(t *testing.T) { + var seen *http.Request + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { seen = r })) + defer up.Close() + f := t.TempDir() + "/secret" + if err := os.WriteFile(f, []byte("0123456789abcdef0123\n"), 0o600); err != nil { + t.Fatal(err) + } + a := &App{cfg: &Config{IPAM: IPAMConfig{URL: up.URL + "/netbox/", UILoginFile: f}}, ipam: &netBox{base: up.URL + "/netbox", client: up.Client()}} + h, err := a.netboxProxy() + if err != nil { + t.Fatal(err) + } + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "https://rollcall.example/netbox/", nil)) + if seen.Header.Get("X-Rollcall-User") != "" || seen.Header.Get("X-Rollcall-Proxy-Secret") != "" { + t.Fatal("signed in without a certificate") + } + if err := os.WriteFile(f, []byte("short"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := a.netboxProxy(); err == nil { + t.Fatal("a short secret was taken") + } +} diff --git a/cmd/rollcall/server.go b/cmd/rollcall/server.go index 3e0f301..b70b2c7 100644 --- a/cmd/rollcall/server.go +++ b/cmd/rollcall/server.go @@ -288,9 +288,13 @@ func (a *App) routes() http.Handler { mux.HandleFunc("POST /api/v1/racks/positions", a.adminAuth(a.handleRackPositions)) mux.HandleFunc("GET /api/v1/cabling", a.adminAuth(a.handleCabling)) if p := a.netboxUIPath(); p != "" { // per method: a bare path would clash with "GET /" below - h := a.adminAuth(a.netboxProxy().ServeHTTP) - for _, m := range []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"} { - mux.HandleFunc(m+" "+p+"/", h) + if px, err := a.netboxProxy(); err != nil { + log.Printf("netbox ui: %v; not served", err) + } else { + h := a.adminAuth(px.ServeHTTP) + for _, m := range []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"} { + mux.HandleFunc(m+" "+p+"/", h) + } } } mux.HandleFunc("POST /api/v1/switches", a.adminAuth(a.handleSwitches)) diff --git a/lab/netbox/install.sh b/lab/netbox/install.sh index 83696a1..f0b16d6 100644 --- a/lab/netbox/install.sh +++ b/lab/netbox/install.sh @@ -6,6 +6,11 @@ # NetBox lives under /netbox/ (BASE_PATH) so the region can serve its UI # through Rollcall (cmd/rollcall/nbproxy.go): Rollcall's ipam url is then # http://$MYIP/netbox/, and ROLLCALL_ORIGINS are where browsers post from. +# The admin certificate signs in to NetBox through that proxy: NetBox takes +# the user from X-Rollcall-User (REMOTE_AUTH), and Caddy drops that header +# unless the request comes from ROLLCALL_IP with ROLLCALL_UI_SECRET (copy it +# to the region's ipam.ui_login_secret_file). Such users land in the group +# rollcall-admins, which may do everything (a lab). # # Run as root inside the container; rerunnable. Secrets are generated here: # /etc/lab-netbox/secrets.env (admin password, Rollcall's API token) @@ -20,6 +25,7 @@ NETBOX_VERSION=${NETBOX_VERSION:-4.7.4} MYIP=${MYIP:-10.213.77.6} SITE=${SITE:-lab} ROLLCALL_ORIGINS=${ROLLCALL_ORIGINS:-"https://10.0.0.234 https://10.213.77.1"} +ROLLCALL_IP=${ROLLCALL_IP:-10.213.77.1} PREFIXES=${PREFIXES:-"10.213.77.0/24 10.213.78.0/24 10.213.79.0/24 fd00:213:77::/64 fd00:213:78::/64"} export DEBIAN_FRONTEND=noninteractive @@ -41,6 +47,7 @@ ROLLCALL_PASS=$(r 18) EOF chmod 600 $S fi +grep -q '^ROLLCALL_UI_SECRET=' $S || echo "ROLLCALL_UI_SECRET=$(python3 -c 'import secrets;print(secrets.token_urlsafe(32))')" >> $S . $S # ------------------------------------------------------------------ PostgreSQL, Valkey @@ -74,6 +81,11 @@ SECRET_KEY = '$NETBOX_SECRET_KEY' API_TOKEN_PEPPERS = {1: '$NETBOX_PEPPER'} TIME_ZONE = 'Europe/Stockholm' BASE_PATH = 'netbox/' +REMOTE_AUTH_ENABLED = True +REMOTE_AUTH_BACKEND = 'netbox.authentication.RemoteUserBackend' +REMOTE_AUTH_HEADER = 'HTTP_X_ROLLCALL_USER' +REMOTE_AUTH_AUTO_CREATE_USER = True +REMOTE_AUTH_DEFAULT_GROUPS = ['rollcall-admins'] CSRF_TRUSTED_ORIGINS = ['http://$MYIP'$(for o in $ROLLCALL_ORIGINS; do printf ", '%s'" "$o"; done)] EOF chown -R netbox:netbox $D/netbox/media $D/netbox/reports $D/netbox/scripts 2>/dev/null || true @@ -89,6 +101,13 @@ systemctl restart netbox netbox-rq cat > /etc/caddy/Caddyfile <