A continuation of HomeBox the inventory and organization system built for the Home User
chore: notifier hardening
Matthew Kilgoreacd9a2334cc0
diff --git a/backend/app/api/handlers/v1/v1_ctrl_notifiers.go b/backend/app/api/handlers/v1/v1_ctrl_notifiers.goindex b6edbb61..a1db18bb 100644--- a/backend/app/api/handlers/v1/v1_ctrl_notifiers.go+++ b/backend/app/api/handlers/v1/v1_ctrl_notifiers.go@@ -5,7 +5,6 @@ import ("github.com/google/uuid""github.com/hay-kot/httpkit/errchain"- "github.com/nicholas-fedor/shoutrrr""github.com/sysadminsmedia/homebox/backend/internal/core/services""github.com/sysadminsmedia/homebox/backend/internal/data/repo""github.com/sysadminsmedia/homebox/backend/internal/sys/validate"@@ -117,7 +116,9 @@ func (ctrl *V1Controller) HandlerNotifierTest() errchain.HandlerFunc {return nil, validate.NewRequestError(err, http.StatusBadRequest)}- err := shoutrrr.Send(q.URL, "Test message from Homebox")+ // Deliver through the guarded client so redirect hops and the resolved+ // address are re-checked against the same policy.+ err := validate.SendNotifierMessage(q.URL, "Test message from Homebox", &ctrl.config.Notifier)return nil, err}diff --git a/backend/app/api/main.go b/backend/app/api/main.goindex cc9afab8..f7018323 100644--- a/backend/app/api/main.go+++ b/backend/app/api/main.go@@ -125,11 +125,11 @@ func run(cfg *config.Config) error {}hasher.SetAPIKeyPepper([]byte(cfg.Auth.APIKeyPepper))- // Harden http.DefaultClient so notifier redirects are re-validated against the- // SSRF policy on every hop. shoutrrr's generic service delivers via- // http.DefaultClient with no CheckRedirect, so without this a notifier that- // passes the initial URL gate could be 30x-redirected to localhost / cloud- // metadata / other blocked destinations. Installed before any notifier can fire.+ // Backstop only: harden http.DefaultClient so any redirect made through it is+ // re-validated against the notifier SSRF policy. Notifier delivery itself goes+ // through validate.SendNotifierMessage, which supplies its own guarded client —+ // shoutrrr builds its own clients and never touches http.DefaultClient, so a+ // guard installed here alone never ran on the delivery path.validate.InstallNotifierRedirectGuard(&cfg.Notifier)// =========================================================================diff --git a/backend/internal/core/services/service_background.go b/backend/internal/core/services/service_background.goindex 29fbc6a4..64ddadf9 100644--- a/backend/internal/core/services/service_background.go+++ b/backend/internal/core/services/service_background.go@@ -9,7 +9,6 @@ import ("time""github.com/google/uuid"- "github.com/nicholas-fedor/shoutrrr""github.com/rs/zerolog/log""github.com/sysadminsmedia/homebox/backend/internal/data/repo""github.com/sysadminsmedia/homebox/backend/internal/data/types"@@ -91,7 +90,7 @@ func (svc *BackgroundService) SendNotifiersToday(ctx context.Context) error {continue}- err := shoutrrr.Send(notifiers[i].URL, bldr.String())+ err := validate.SendNotifierMessage(notifiers[i].URL, bldr.String(), svc.notifierConfig)if err != nil {sendErrs = append(sendErrs, err)diff --git a/backend/internal/sys/validate/notifier_http.go b/backend/internal/sys/validate/notifier_http.goindex 7459095c..a7fde151 100644--- a/backend/internal/sys/validate/notifier_http.go+++ b/backend/internal/sys/validate/notifier_http.go@@ -1,9 +1,14 @@package validateimport (+ "context""fmt"+ "net""net/http"+ "time"+ "github.com/nicholas-fedor/shoutrrr/pkg/router"+ "github.com/nicholas-fedor/shoutrrr/pkg/types""github.com/sysadminsmedia/homebox/backend/internal/sys/config")@@ -11,24 +16,105 @@ import (// default so behavior is unchanged for legitimate redirect chains.const maxNotifierRedirects = 10-// InstallNotifierRedirectGuard hardens http.DefaultClient so redirects are-// re-validated against the notifier SSRF policy on every hop.-//-// shoutrrr's generic service performs its HTTP request with http.DefaultClient and-// no CheckRedirect hook, so a host that passes the initial ValidateNotifierURL gate-// can respond with a 30x redirect to localhost / link-local / cloud-metadata / any-// other blocked destination, and the follow-up hop is delivered without re-checking-// the policy — bypassing the SSRF guards. Re-validating each hop closes that hole.+// notifierHTTPTimeout bounds a single notifier delivery.+const notifierHTTPTimeout = 30 * time.Second++// InstallNotifierRedirectGuard hardens http.DefaultClient so redirects made through+// it are re-validated against the notifier SSRF policy on every hop.//-// This affects every http.DefaultClient consumer in the process, but in Homebox-// that is only shoutrrr: all other outbound HTTP clients (labelmaker, analytics,-// otel, product search, the GitHub release check) are constructed explicitly. The-// guard only rejects redirects whose target is blocked by policy; ordinary-// redirects to permitted hosts continue to be followed.+// This is only a backstop. shoutrrr does not use http.DefaultClient: its services+// build their own clients, and shoutrrr.Send routes through a package-level router+// that never injects one, so a guard installed here never ran on the delivery path.+// SendNotifierMessage is the enforced path — it supplies NotifierHTTPClient, which+// carries the same redirect guard plus a policy-checked dialer. This call remains so+// that any other code reaching for http.DefaultClient is covered too.func InstallNotifierRedirectGuard(cfg *config.NotifierConf) {http.DefaultClient.CheckRedirect = NotifierRedirectGuard(cfg)}+// SendNotifierMessage validates rawURL against the SSRF policy and, if it passes,+// delivers message through NotifierHTTPClient.+//+// Validation and delivery are deliberately bundled: shoutrrr.Send would otherwise+// send through an unguarded client, so a caller that forgot the validation step —+// or a scheme the initial gate did not cover — would reach the network unchecked.+func SendNotifierMessage(rawURL, message string, cfg *config.NotifierConf) error {+ if err := ValidateNotifierURL(rawURL, cfg); err != nil {+ return err+ }++ sender, err := router.NewWithOptions(nil, types.SenderOptions{+ HTTPClient: NotifierHTTPClient(cfg),+ Timeout: notifierHTTPTimeout,+ })+ if err != nil {+ return fmt.Errorf("creating notifier sender: %w", err)+ }++ return sender.Route(rawURL, message)+}++// NotifierHTTPClient returns the HTTP client used to deliver notifications. It+// enforces the SSRF policy at two points the initial URL check cannot cover:+//+// - CheckRedirect re-validates the target of every redirect hop, so a host that+// passes the URL gate cannot 30x the request onward to a blocked destination.+// - DialContext resolves each hostname itself, validates the addresses it got+// back, and then dials one of those exact addresses. Re-using the validated+// address instead of letting the transport resolve the name again closes the+// DNS-rebinding window between validation and connection.+func NotifierHTTPClient(cfg *config.NotifierConf) *http.Client {+ client := &http.Client{+ Timeout: notifierHTTPTimeout,+ CheckRedirect: NotifierRedirectGuard(cfg),+ }++ // With no policy configured there is nothing to enforce at dial time; keep the+ // default transport rather than failing every connection.+ if cfg == nil {+ return client+ }++ transport, ok := http.DefaultTransport.(*http.Transport)+ if !ok {+ return client+ }++ guarded := transport.Clone()+ dialer := &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}++ guarded.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {+ host, port, err := net.SplitHostPort(addr)+ if err != nil {+ return nil, fmt.Errorf("invalid notifier address %q: %w", addr, err)+ }++ ips, err := resolveHostForPolicy(ctx, host, cfg)+ if err != nil {+ return nil, fmt.Errorf("notifier destination %q blocked by SSRF policy: %w", host, err)+ }++ var lastErr error+ for _, ip := range ips {+ conn, dialErr := dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))+ if dialErr == nil {+ return conn, nil+ }+ lastErr = dialErr+ }++ if lastErr == nil {+ lastErr = fmt.Errorf("no addresses available for %q", host)+ }++ return nil, lastErr+ }++ client.Transport = guarded++ return client+}+// NotifierRedirectGuard returns an http.Client CheckRedirect hook that refuses any// redirect whose target resolves to an address blocked by cfg, and caps the number// of hops. Returning a non-nil error aborts the request with that error rather thandiff --git a/backend/internal/sys/validate/notifier_ssrf_redirect_test.go b/backend/internal/sys/validate/notifier_ssrf_redirect_test.goindex b2b31c4f..80a325d0 100644--- a/backend/internal/sys/validate/notifier_ssrf_redirect_test.go+++ b/backend/internal/sys/validate/notifier_ssrf_redirect_test.go@@ -3,68 +3,125 @@ package validate_testimport ("net/http""net/http/httptest"+ "net/url""sync/atomic""testing"- "github.com/nicholas-fedor/shoutrrr""github.com/stretchr/testify/assert""github.com/stretchr/testify/require""github.com/sysadminsmedia/homebox/backend/internal/sys/config""github.com/sysadminsmedia/homebox/backend/internal/sys/validate")-// startVictimAndRedirector spins up two loopback servers: a "victim" that records-// whether it was reached, and a "redirector" that 307-redirects any request to the-// victim. It returns the generic+ notifier URL pointing at the redirector and a-// function reporting how many times the victim was hit.-func startVictimAndRedirector(t *testing.T) (notifierURL string, victimHits func() int32) {+// startVictim spins up a loopback server that records whether it was reached.+func startVictim(t *testing.T) (serverURL string, hits func() int32) {t.Helper()- var hits int32+ var count int32victim := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {- atomic.AddInt32(&hits, 1)+ atomic.AddInt32(&count, 1)w.WriteHeader(http.StatusOK)}))t.Cleanup(victim.Close)- redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {- w.Header().Set("Location", victim.URL)- w.WriteHeader(http.StatusTemporaryRedirect)- }))- t.Cleanup(redirector.Close)+ return victim.URL, func() int32 { return atomic.LoadInt32(&count) }+}++// TestNotifierRedirectGuard_RefusesBlockedHop verifies the CheckRedirect hook refuses+// a hop whose target is blocked by policy. Without it, a host that passes the initial+// URL gate could 30x the request onward to localhost / link-local / cloud metadata.+func TestNotifierRedirectGuard_RefusesBlockedHop(t *testing.T) {+ guard := validate.NotifierRedirectGuard(&config.NotifierConf{BlockLocalhost: true})++ blocked, err := url.Parse("http://127.0.0.1:8080/webhook")+ require.NoError(t, err)++ err = guard(&http.Request{URL: blocked}, nil)+ assert.Error(t, err, "a redirect to a blocked destination must be refused")+}++// TestNotifierRedirectGuard_AllowsPermittedHop ensures ordinary redirects to+// permitted hosts continue to be followed.+func TestNotifierRedirectGuard_AllowsPermittedHop(t *testing.T) {+ guard := validate.NotifierRedirectGuard(&config.NotifierConf{})++ allowed, err := url.Parse("http://127.0.0.1:8080/webhook")+ require.NoError(t, err)++ err = guard(&http.Request{URL: allowed}, nil)+ assert.NoError(t, err, "with no blocks configured the redirect must be followed")+}++// TestNotifierRedirectGuard_CapsHops verifies the hop cap still applies.+func TestNotifierRedirectGuard_CapsHops(t *testing.T) {+ guard := validate.NotifierRedirectGuard(&config.NotifierConf{})- // shoutrrr's generic service wraps a plain http(s) URL as generic+http(s)://...- return "generic+" + redirector.URL, func() int32 { return atomic.LoadInt32(&hits) }+ target, err := url.Parse("http://example.com/webhook")+ require.NoError(t, err)++ err = guard(&http.Request{URL: target}, make([]*http.Request, 10))+ assert.Error(t, err, "the redirect chain must be capped")+}++// TestNotifierHTTPClient_BlocksDestination verifies the client's dialer enforces the+// policy on the very first hop. The previous guard lived only on CheckRedirect, which+// net/http invokes before *following* a redirect and never for the initial request,+// so the first hop was never checked at connection time.+func TestNotifierHTTPClient_BlocksDestination(t *testing.T) {+ victimURL, victimHits := startVictim(t)++ client := validate.NotifierHTTPClient(&config.NotifierConf{BlockLocalhost: true})++ resp, err := client.Get(victimURL) //nolint:noctx // exercising the dialer, not a real request path+ if err == nil {+ _ = resp.Body.Close()+ }++ require.Error(t, err, "a blocked destination must be refused at dial time")+ assert.Equal(t, int32(0), victimHits(), "the blocked destination must never be reached")}-// TestNotifierRedirectSSRF_Unguarded documents the vulnerability: shoutrrr's generic-// service delivers via http.DefaultClient, which follows redirects with no policy-// re-check. A host that passes the initial SSRF gate can 307-redirect to a blocked-// destination (here loopback) and the follow-up hop is delivered.-func TestNotifierRedirectSSRF_Unguarded(t *testing.T) {- // Ensure default redirect-following behavior for this case.- saved := http.DefaultClient.CheckRedirect- http.DefaultClient.CheckRedirect = nil- t.Cleanup(func() { http.DefaultClient.CheckRedirect = saved })+// TestNotifierHTTPClient_AllowsPermittedDestination ensures the guarded client still+// delivers to destinations the policy permits.+func TestNotifierHTTPClient_AllowsPermittedDestination(t *testing.T) {+ victimURL, victimHits := startVictim(t)- notifierURL, victimHits := startVictimAndRedirector(t)+ client := validate.NotifierHTTPClient(&config.NotifierConf{})- err := shoutrrr.Send(notifierURL, "Test message from Homebox")+ resp, err := client.Get(victimURL) //nolint:noctx // exercising the dialer, not a real request pathrequire.NoError(t, err)- assert.Equal(t, int32(1), victimHits(), "unguarded: redirect to loopback victim IS followed (SSRF)")+ _ = resp.Body.Close()++ assert.Equal(t, int32(1), victimHits(), "a permitted destination must still be reached")+}++// TestSendNotifierMessage_EnforcesPolicy verifies the send path validates the URL+// before delivering. shoutrrr.Send would otherwise deliver through an unguarded+// client of its own.+func TestSendNotifierMessage_EnforcesPolicy(t *testing.T) {+ victimURL, victimHits := startVictim(t)++ err := validate.SendNotifierMessage(+ "generic+"+victimURL,+ "Test message from Homebox",+ &config.NotifierConf{BlockLocalhost: true},+ )++ require.Error(t, err, "a blocked destination must not be delivered to")+ assert.Equal(t, int32(0), victimHits(), "the blocked destination must never be reached")}-// TestNotifierRedirectSSRF_Guarded verifies the fix: with the redirect guard-// installed on http.DefaultClient, a 307 to a blocked (loopback) destination is-// refused, the send fails, and the victim is never reached.-func TestNotifierRedirectSSRF_Guarded(t *testing.T) {- saved := http.DefaultClient.CheckRedirect- http.DefaultClient.CheckRedirect = validate.NotifierRedirectGuard(&config.NotifierConf{BlockLocalhost: true})- t.Cleanup(func() { http.DefaultClient.CheckRedirect = saved })+// TestSendNotifierMessage_DeliversPermitted ensures the guarded send path still+// delivers notifications the policy permits.+func TestSendNotifierMessage_DeliversPermitted(t *testing.T) {+ victimURL, victimHits := startVictim(t)- notifierURL, victimHits := startVictimAndRedirector(t)+ err := validate.SendNotifierMessage(+ "generic+"+victimURL,+ "Test message from Homebox",+ &config.NotifierConf{},+ )- err := shoutrrr.Send(notifierURL, "Test message from Homebox")- require.Error(t, err, "guarded: redirect to loopback must be refused and the send must fail")- assert.Equal(t, int32(0), victimHits(), "guarded: the blocked redirect target must never be reached")+ require.NoError(t, err)+ assert.Equal(t, int32(1), victimHits(), "a permitted notifier must still be delivered")}diff --git a/backend/internal/sys/validate/notifier_url.go b/backend/internal/sys/validate/notifier_url.goindex 7014c1f5..02ee6713 100644--- a/backend/internal/sys/validate/notifier_url.go+++ b/backend/internal/sys/validate/notifier_url.go@@ -1,6 +1,7 @@package validateimport (+ "context""fmt""net""net/url"@@ -10,32 +11,152 @@ import ("github.com/sysadminsmedia/homebox/backend/internal/sys/config")-// ValidateNotifierURL validates a notifier URL against the configured block/allow lists.-// This only applies to generic:// notifier URLs which can make arbitrary HTTP requests.-func ValidateNotifierURL(notifierURL string, cfg *config.NotifierConf) error {- // Only validate generic notifiers- if !isGenericNotifier(notifierURL) {- return nil- }+// genericScheme is the shoutrrr service name for the generic webhook service.+const genericScheme = "generic"++// notifierHostSource describes where a notifier scheme's network destination+// comes from, which determines whether the SSRF policy has a host to check.+type notifierHostSource int++const (+ // hostIsIdentifier means the URL's host component is an account, token,+ // channel or webhook identifier rather than a hostname. The service always+ // connects to a fixed vendor endpoint, so no user-controlled destination+ // reaches the network layer and there is nothing for the policy to check.+ hostIsIdentifier notifierHostSource = iota+ // hostFromURL means the URL's host component is the server the service+ // connects to, chosen freely by whoever supplied the URL.+ hostFromURL+ // hostFromWrappedURL means the scheme wraps a full HTTP(S) URL whose host+ // is the destination (generic://).+ hostFromWrappedURL+)+// notifierSchemes classifies every service in shoutrrr's registry by where its+// network destination comes from. Anything not listed here is rejected: failing+// closed means a service added by a future shoutrrr upgrade cannot silently+// escape the SSRF policy, at the cost of needing an entry added here first.+//+// The policy previously applied only to generic://, on the assumption that it+// was the only scheme able to reach an arbitrary host. That was wrong — gotify,+// ntfy, mattermost, matrix and others all take a fully user-supplied host, and+// several accept a disabletls/scheme parameter that downgrades the connection to+// plaintext HTTP against that host. Those URLs bypassed the allow/block lists+// entirely, including the block_bogon_nets and block_cloud_metadata rules that+// are enabled by default.+var notifierSchemes = map[string]notifierHostSource{+ genericScheme: hostFromWrappedURL,++ // The URL host is the server the notifier connects to.+ "bark": hostFromURL,+ "googlechat": hostFromURL,+ "gotify": hostFromURL,+ "hangouts": hostFromURL,+ "lark": hostFromURL,+ "matrix": hostFromURL,+ "mattermost": hostFromURL,+ "mqtt": hostFromURL,+ "mqtts": hostFromURL,+ "ntfy": hostFromURL,+ "opsgenie": hostFromURL,+ "pagerduty": hostFromURL,+ "rocketchat": hostFromURL,+ "signal": hostFromURL,+ "smtp": hostFromURL,+ "zulip": hostFromURL,++ // The URL host is an identifier; the service talks to a fixed vendor+ // endpoint (teams takes its webhook URL from a query parameter that+ // shoutrrr itself restricts to Microsoft workflow domains).+ "discord": hostIsIdentifier,+ "ifttt": hostIsIdentifier,+ "join": hostIsIdentifier,+ "logger": hostIsIdentifier,+ "notifiarr": hostIsIdentifier,+ "pushbullet": hostIsIdentifier,+ "pushover": hostIsIdentifier,+ "slack": hostIsIdentifier,+ "teams": hostIsIdentifier,+ "telegram": hostIsIdentifier,+ "twilio": hostIsIdentifier,+ "wecom": hostIsIdentifier,+}++// ValidateNotifierURL validates a notifier URL against the configured block/allow+// lists. Every scheme that carries a user-supplied network destination is checked,+// not just generic://, and unknown schemes are rejected outright.+func ValidateNotifierURL(notifierURL string, cfg *config.NotifierConf) error {// Defensively guard against nil cfgif cfg == nil {return fmt.Errorf("notifier configuration is nil, cannot validate URL")}- // Extract the actual URL from the generic:// wrapper- actualURL, err := extractGenericURL(notifierURL)- if err != nil {- return fmt.Errorf("invalid generic notifier URL: %w", err)+ scheme, _, ok := splitScheme(notifierURL)+ if !ok {+ return fmt.Errorf("notifier URL is missing a scheme")}- // Parse the URL to extract the hostname- parsedURL, err := url.Parse(actualURL)- if err != nil {- return fmt.Errorf("invalid URL in generic notifier: %w", err)+ // shoutrrr routes on the part before the "+" (generic+http -> generic).+ service, _, _ := strings.Cut(scheme, "+")++ source, known := notifierSchemes[service]+ if !known {+ return fmt.Errorf("unsupported notifier scheme %q", service)+ }++ switch source {+ case hostFromWrappedURL:+ // Extract the actual URL from the generic:// wrapper+ actualURL, err := extractGenericURL(notifierURL)+ if err != nil {+ return fmt.Errorf("invalid generic notifier URL: %w", err)+ }++ // Parse the URL to extract the hostname+ parsedURL, err := url.Parse(actualURL)+ if err != nil {+ return fmt.Errorf("invalid URL in generic notifier: %w", err)+ }++ return validateHostAgainstPolicy(parsedURL.Hostname(), cfg)++ case hostFromURL:+ parsedURL, err := url.Parse(notifierURL)+ if err != nil {+ return fmt.Errorf("invalid notifier URL: %w", err)+ }++ host := parsedURL.Hostname()+ if host == "" {+ // No host means the service falls back to its own vendor default+ // endpoint, so there is no user-controlled destination to check.+ return nil+ }++ return validateHostAgainstPolicy(host, cfg)++ case hostIsIdentifier:+ return nil}- return validateHostAgainstPolicy(parsedURL.Hostname(), cfg)+ return nil+}++// splitScheme splits a notifier URL into its lower-cased scheme and the remainder+// after "://".+//+// URL schemes are case-insensitive (RFC 3986 section 3.1), and both net/url and+// shoutrrr's router lower-case the scheme before dispatching, so the policy has to+// match on the same normalized form. Matching the raw string meant "generic+HTTP://"+// routed to the generic webhook service while every prefix test here returned false,+// skipping validation entirely.+func splitScheme(notifierURL string) (scheme, rest string, ok bool) {+ i := strings.Index(notifierURL, "://")+ if i < 0 {+ return "", "", false+ }++ return strings.ToLower(notifierURL[:i]), notifierURL[i+len("://"):], true}// validateHostAgainstPolicy resolves host and checks every resolved IP (plus any@@ -44,54 +165,75 @@ func ValidateNotifierURL(notifierURL string, cfg *config.NotifierConf) error {// redirect hop at delivery time) so both enforce identical rules — the redirect// path previously escaped these checks entirely, which was the SSRF bypass.func validateHostAgainstPolicy(host string, cfg *config.NotifierConf) error {+ _, err := resolveHostForPolicy(context.Background(), host, cfg)++ return err+}++// resolveHostForPolicy resolves host, enforces the allow/block policy against every+// resolved address, and returns the addresses that were checked so a caller can dial+// exactly what it validated. Dialing the returned addresses rather than re-resolving+// the name is what closes the DNS-rebinding window between validation and delivery.+func resolveHostForPolicy(ctx context.Context, host string, cfg *config.NotifierConf) ([]net.IP, error) {if cfg == nil {- return fmt.Errorf("notifier configuration is nil, cannot validate URL")+ return nil, fmt.Errorf("notifier configuration is nil, cannot validate URL")}if host == "" {- return fmt.Errorf("no hostname found in URL")+ return nil, fmt.Errorf("no hostname found in URL")}// Resolve the hostname to an IP address- // NOTE: DNS responses can change after validation; consider re-validating at request time.- ips, err := net.LookupIP(host)+ addrs, err := net.DefaultResolver.LookupIPAddr(ctx, host)if err != nil {- return fmt.Errorf("failed to resolve hostname: %w", err)+ return nil, fmt.Errorf("failed to resolve hostname: %w", err)+ }++ if len(addrs) == 0 {+ return nil, fmt.Errorf("hostname did not resolve to any IP addresses")}- if len(ips) == 0 {- return fmt.Errorf("hostname did not resolve to any IP addresses")+ resolved := make([]net.IP, 0, len(addrs))+ for _, addr := range addrs {+ resolved = append(resolved, addr.IP)}// Expand DNS64-synthesized IPv6 addresses (RFC 6052) into their embedded// IPv4 addresses so the allow/block rules below are applied to the IPv4// destination the NAT64 gateway will actually reach. The original IPv6// address stays in the list so IPv6 rules still apply to it.- checkIPs := make([]net.IP, 0, len(ips))- for _, ip := range ips {+ checkIPs := make([]net.IP, 0, len(resolved))+ for _, ip := range resolved {checkIPs = append(checkIPs, ip)embedded, inDNS64Range := dns64EmbeddedIPv4s(ip, cfg.Dns64Nets)if inDNS64Range && len(embedded) == 0 {- return fmt.Errorf("IP %s is in a DNS64 range but no valid embedded IPv4 address could be extracted", ip.String())+ return nil, fmt.Errorf("IP %s is in a DNS64 range but no valid embedded IPv4 address could be extracted", ip.String())}checkIPs = append(checkIPs, embedded...)}- ips = checkIPs// If AllowNets is configured it acts as an allowlist: every IP must match,// and passing skips the remaining block checks.if len(cfg.AllowNets) > 0 {- return checkAllowNets(ips, cfg.AllowNets)+ if err := checkAllowNets(checkIPs, cfg.AllowNets); err != nil {+ return nil, err+ }++ return resolved, nil}// Check BlockNets - block specific networks if configuredif len(cfg.BlockNets) > 0 {- if err := checkBlockNets(ips, cfg.BlockNets); err != nil {- return err+ if err := checkBlockNets(checkIPs, cfg.BlockNets); err != nil {+ return nil, err}}- return checkBlockedCategories(ips, cfg)+ if err := checkBlockedCategories(checkIPs, cfg); err != nil {+ return nil, err+ }++ return resolved, nil}// checkAllowNets verifies every IP falls within one of the allowNets. A nil@@ -170,36 +312,54 @@ func checkBlockedCategories(ips []net.IP, cfg *config.NotifierConf) error {return nil}-// isGenericNotifier checks if the URL is a generic notifier that needs validation+// isGenericNotifier checks if the URL is a generic notifier that needs validation.+// The scheme is matched case-insensitively, matching how shoutrrr routes it.func isGenericNotifier(notifierURL string) bool {- return strings.HasPrefix(notifierURL, "generic://") ||- strings.HasPrefix(notifierURL, "generic+https://") ||- strings.HasPrefix(notifierURL, "generic+http://")+ scheme, _, ok := splitScheme(notifierURL)+ if !ok {+ return false+ }++ service, transport, hasTransport := strings.Cut(scheme, "+")+ if service != genericScheme {+ return false+ }++ return !hasTransport || transport == "http" || transport == "https"}// extractGenericURL extracts the actual HTTP(S) URL from a generic notifier URLfunc extractGenericURL(notifierURL string) (string, error) {- if strings.HasPrefix(notifierURL, "generic://") {- rawURL := strings.TrimPrefix(notifierURL, "generic://")+ scheme, rest, ok := splitScheme(notifierURL)+ if !ok {+ return "", fmt.Errorf("not a generic notifier URL")+ }- if rawURL == "" {- return "", fmt.Errorf("generic notifier URL is empty")- }+ service, transport, hasTransport := strings.Cut(scheme, "+")+ if service != genericScheme {+ return "", fmt.Errorf("not a generic notifier URL")+ }- // Support shorthand generic://host/path by defaulting to HTTPS.- if strings.HasPrefix(rawURL, "http://") || strings.HasPrefix(rawURL, "https://") {- return rawURL, nil+ // generic+http:// and generic+https:// carry the transport in the scheme.+ if hasTransport {+ if transport != "http" && transport != "https" {+ return "", fmt.Errorf("unsupported generic notifier transport %q", transport)}- return "https://" + rawURL, nil+ return transport + "://" + rest, nil}- if strings.HasPrefix(notifierURL, "generic+https://") {- return strings.TrimPrefix(notifierURL, "generic+"), nil++ if rest == "" {+ return "", fmt.Errorf("generic notifier URL is empty")}- if strings.HasPrefix(notifierURL, "generic+http://") {- return strings.TrimPrefix(notifierURL, "generic+"), nil++ // Support the nested generic://http://host/path form.+ if lower := strings.ToLower(rest); strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") {+ return rest, nil}- return "", fmt.Errorf("not a generic notifier URL")++ // Support shorthand generic://host/path by defaulting to HTTPS.+ return "https://" + rest, nil}// rfc6052PrefixLens are the prefix lengths at which RFC 6052 permits embeddingdiff --git a/backend/internal/sys/validate/notifier_url_test.go b/backend/internal/sys/validate/notifier_url_test.goindex 92134aba..736c77c2 100644--- a/backend/internal/sys/validate/notifier_url_test.go+++ b/backend/internal/sys/validate/notifier_url_test.go@@ -669,3 +669,115 @@ func TestValidateNotifierURL_InvalidCIDR_BlockNets(t *testing.T) {})}}++// TestValidateNotifierURL_SchemeCaseBypass covers the bypass where the SSRF policy+// matched the raw URL string case-sensitively while shoutrrr lower-cases the scheme+// before routing, so an upper-cased scheme reached the generic webhook service with+// no validation at all.+func TestValidateNotifierURL_SchemeCaseBypass(t *testing.T) {+ cfg := config.NotifierConf{+ BlockLocalhost: true,+ BlockLocalNets: true,+ BlockBogonNets: true,+ BlockCloudMetadata: true,+ }++ blocked := []string{+ "generic+HTTP://169.254.169.254/latest/meta-data",+ "generic+HTTPS://127.0.0.1/webhook",+ "GENERIC+HTTP://169.254.169.254/latest/meta-data",+ "GENERIC://http://127.0.0.1:8080/webhook",+ "Generic+Http://192.168.1.1/webhook",+ }++ for _, url := range blocked {+ t.Run(url, func(t *testing.T) {+ if err := ValidateNotifierURL(url, &cfg); err == nil {+ t.Errorf("expected %q to be blocked, but validation passed", url)+ }+ })+ }+}++// TestValidateNotifierURL_NonGenericSchemes covers the bypass where the policy was+// applied only to generic:// URLs, while schemes such as gotify and ntfy take a+// fully user-supplied host (and a disabletls/scheme parameter that downgrades the+// connection to plaintext HTTP against it).+func TestValidateNotifierURL_NonGenericSchemes(t *testing.T) {+ cfg := config.NotifierConf{+ BlockLocalhost: true,+ BlockLocalNets: true,+ BlockBogonNets: true,+ BlockCloudMetadata: true,+ }++ blocked := []string{+ "gotify://127.0.0.1:9000/AAAAAAAAAAAAAAA?disabletls=yes",+ "ntfy://169.254.169.254/latest/meta-data?scheme=http",+ "NTFY://169.254.169.254/topic",+ "mattermost://192.168.1.1/token?disabletls=yes",+ "matrix://user:[email protected]/",+ "smtp://user:[email protected]:587/",+ "zulip://bot:[email protected]/",+ "rocketchat://10.0.0.1/token",+ }++ for _, url := range blocked {+ t.Run(url, func(t *testing.T) {+ if err := ValidateNotifierURL(url, &cfg); err == nil {+ t.Errorf("expected %q to be blocked, but validation passed", url)+ }+ })+ }+}++// TestValidateNotifierURL_IdentifierHostsAllowed ensures schemes whose URL "host" is+// an account/token/channel identifier rather than a hostname are not rejected by the+// host policy — they always talk to a fixed vendor endpoint.+func TestValidateNotifierURL_IdentifierHostsAllowed(t *testing.T) {+ cfg := config.NotifierConf{+ BlockLocalhost: true,+ BlockLocalNets: true,+ BlockBogonNets: true,+ BlockCloudMetadata: true,+ }++ allowed := []string{+ "discord://token@id",+ "slack://token:token@channel",+ "telegram://token@telegram?chats=1",+ "pushover://shoutrrr:apiToken@userKey/",+ "pushbullet://tokentokentoken",+ "DISCORD://token@id",+ }++ for _, url := range allowed {+ t.Run(url, func(t *testing.T) {+ if err := ValidateNotifierURL(url, &cfg); err != nil {+ t.Errorf("expected %q to pass, got: %v", url, err)+ }+ })+ }+}++// TestValidateNotifierURL_UnknownSchemeRejected ensures the policy fails closed for+// schemes it does not know how to classify, rather than letting them through.+func TestValidateNotifierURL_UnknownSchemeRejected(t *testing.T) {+ cfg := config.NotifierConf{BlockLocalhost: true}++ rejected := []string{+ "file:///etc/passwd",+ "gopher://127.0.0.1:11211/_stats",+ "somethingnew://127.0.0.1/x",+ "generic+ftp://127.0.0.1/x",+ "not-a-url",+ }++ for _, url := range rejected {+ t.Run(url, func(t *testing.T) {+ if err := ValidateNotifierURL(url, &cfg); err == nil {+ t.Errorf("expected %q to be rejected, but validation passed", url)+ }+ })+ }+}diff --git a/backend/internal/sys/validate/validate.go b/backend/internal/sys/validate/validate.goindex d9dbe24f..4a79b1b9 100644--- a/backend/internal/sys/validate/validate.go+++ b/backend/internal/sys/validate/validate.go@@ -12,42 +12,47 @@ var validate *validator.Validatefunc init() { // nolintvalidate = validator.New()- err := validate.RegisterValidation("shoutrrr", func(fl validator.FieldLevel) bool {- prefixes := [...]string{- "bark://",- "discord://",- "smtp://",- "gotify://",- "googlechat://",- "ifttt://",- "join://",- "mattermost://",- "matrix://",- "ntfy://",- "opsgenie://",- "pushbullet://",- "pushover://",- "rocketchat://",- "slack://",- "teams://",- "telegram://",- "zulip://",- "generic://",- "generic+",- }+ // Notifier schemes users are allowed to configure. Matching is done on the+ // normalized (lower-cased) scheme rather than a raw prefix: schemes are+ // case-insensitive and shoutrrr lower-cases them before routing, so a raw+ // prefix test disagrees with the service that actually handles the URL.+ allowedNotifierSchemes := map[string]bool{+ "bark": true,+ "discord": true,+ "smtp": true,+ "gotify": true,+ "googlechat": true,+ "ifttt": true,+ "join": true,+ "mattermost": true,+ "matrix": true,+ "ntfy": true,+ "opsgenie": true,+ "pushbullet": true,+ "pushover": true,+ "rocketchat": true,+ "slack": true,+ "teams": true,+ "telegram": true,+ "zulip": true,+ "generic": true,+ }+ err := validate.RegisterValidation("shoutrrr", func(fl validator.FieldLevel) bool {str := fl.Field().String()if str == "" {return false}- for _, prefix := range prefixes {- if strings.HasPrefix(str, prefix) {- return true- }+ scheme, _, ok := splitScheme(str)+ if !ok {+ return false}- return false+ // shoutrrr routes on the part before the "+" (generic+http -> generic).+ service, _, _ := strings.Cut(scheme, "+")++ return allowedNotifierSchemes[service]})if err != nil {