Explorar o código

fix(push): reject non-public web push endpoints (#1626)

Web push subscriptions now require https and a public host, and the notifier resolves the endpoint at send time and refuses loopback, private, link-local, CGNAT, documentation and NAT64 addresses. Redirects are revalidated and the dialer connects to the checked IP, so DNS rebinding cannot reach the LAN. Legacy private rows are skipped without sending.

Closes #1625
Nacho hai 1 mes
pai
achega
2671c7eaf7

+ 4 - 0
server-go/internal/httpapi/push.go

@@ -63,6 +63,10 @@ func (s *server) handlePushSubscribe(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusBadRequest, "invalid_body", "endpoint, keys.auth, keys.p256dh y language (es|en) son obligatorios")
 		return
 	}
+	if err := push.ValidateEndpoint(body.Endpoint); err != nil {
+		writeError(w, http.StatusBadRequest, "invalid_endpoint", err.Error())
+		return
+	}
 	created, err := push.UpsertSubscription(s.db, push.Subscription{
 		Endpoint:  body.Endpoint,
 		Auth:      body.Keys.Auth,

+ 33 - 2
server-go/internal/httpapi/push_api_test.go

@@ -4,6 +4,7 @@
 package httpapi_test
 
 import (
+	"fmt"
 	"io"
 	"strings"
 	"testing"
@@ -93,8 +94,8 @@ func TestPushEndpointsContract(t *testing.T) {
 		`{"endpoint":"","keys":{"auth":"a","p256dh":"p"}}`,
 		`{"endpoint":"https://x/y"}`,
 		`{"endpoint":"https://x/y","keys":{"auth":"","p256dh":"p"}}`,
-		`{"endpoint":"https://x/y","keys":{"auth":"a","p256dh":"p"}}`,               // sin language
-		`{"endpoint":"https://x/y","keys":{"auth":"a","p256dh":"p"},"language":""}`,  // language vacío
+		`{"endpoint":"https://x/y","keys":{"auth":"a","p256dh":"p"}}`,                 // sin language
+		`{"endpoint":"https://x/y","keys":{"auth":"a","p256dh":"p"},"language":""}`,   // language vacío
 		`{"endpoint":"https://x/y","keys":{"auth":"a","p256dh":"p"},"language":"fr"}`, // idioma no soportado
 	} {
 		res = doJSON(t, "POST", ts.URL, "/api/push/subscribe", cookie, bad)
@@ -125,3 +126,33 @@ func TestPushEndpointsContract(t *testing.T) {
 	}
 	res.Body.Close()
 }
+
+func TestPushSubscribeRejectsNonPublicEndpoints(t *testing.T) {
+	ts := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	for _, endpoint := range []string{
+		"http://push.example/x",
+		"https://127.0.0.1/x",
+		"https://192.168.1.10/x",
+		"https://[::1]/x",
+		"https://localhost/x",
+		"https://169.254.169.254/latest/meta-data",
+		"https://user:pass@push.example/x",
+	} {
+		body := fmt.Sprintf(`{"endpoint":%q,"keys":{"auth":"a","p256dh":"p"},"language":"es"}`, endpoint)
+		res := doJSON(t, "POST", ts.URL, "/api/push/subscribe", cookie, body)
+		if res.StatusCode != 400 {
+			t.Fatalf("subscribe %s: %d, esperaba 400", endpoint, res.StatusCode)
+		}
+		res.Body.Close()
+	}
+
+	var n int
+	if err := ts.db.QueryRow("SELECT COUNT(*) FROM push_subscriptions").Scan(&n); err != nil {
+		t.Fatalf("count: %v", err)
+	}
+	if n != 0 {
+		t.Fatalf("suscripciones persistidas: %d, esperaba 0", n)
+	}
+}

+ 161 - 0
server-go/internal/push/endpoint.go

@@ -0,0 +1,161 @@
+package push
+
+import (
+	"context"
+	"crypto/tls"
+	"errors"
+	"fmt"
+	"net"
+	"net/http"
+	"net/url"
+	"strconv"
+	"strings"
+	"time"
+)
+
+const maxRedirects = 5
+
+// ValidateEndpoint accepts only HTTPS endpoints whose host is public. It is
+// used when a subscription is created and again before every send, so rows
+// stored by older versions cannot reach the LAN either.
+func ValidateEndpoint(raw string) error {
+	u, err := url.Parse(raw)
+	if err != nil {
+		return fmt.Errorf("endpoint invalido: %w", err)
+	}
+	if !strings.EqualFold(u.Scheme, "https") {
+		return errors.New("el endpoint debe usar https")
+	}
+	if u.User != nil {
+		return errors.New("el endpoint no puede incluir credenciales")
+	}
+	host := u.Hostname()
+	if host == "" {
+		return errors.New("el endpoint no tiene host")
+	}
+	if port := u.Port(); port != "" {
+		n, err := strconv.Atoi(port)
+		if err != nil || n < 1 || n > 65535 {
+			return errors.New("el endpoint tiene un puerto invalido")
+		}
+	}
+	if ip := net.ParseIP(host); ip != nil {
+		if blockedIP(ip) {
+			return errors.New("el endpoint apunta a una direccion no publica")
+		}
+		return nil
+	}
+	name := strings.ToLower(strings.TrimSuffix(host, "."))
+	if name == "localhost" || strings.HasSuffix(name, ".localhost") {
+		return errors.New("el endpoint apunta a localhost")
+	}
+	return nil
+}
+
+func blockedIP(ip net.IP) bool {
+	if ip == nil {
+		return true
+	}
+	if ip.IsLoopback() || ip.IsPrivate() || ip.IsUnspecified() || ip.IsMulticast() ||
+		ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
+		return true
+	}
+	if v4 := ip.To4(); v4 != nil {
+		switch {
+		case v4[0] == 0:
+			return true
+		case v4[0] == 100 && v4[1] >= 64 && v4[1] <= 127:
+			return true
+		case v4[0] == 192 && v4[1] == 0 && v4[2] == 0:
+			return true
+		case v4[0] == 192 && v4[1] == 0 && v4[2] == 2:
+			return true
+		case v4[0] == 198 && (v4[1] == 18 || v4[1] == 19):
+			return true
+		case v4[0] == 198 && v4[1] == 51 && v4[2] == 100:
+			return true
+		case v4[0] == 203 && v4[1] == 0 && v4[2] == 113:
+			return true
+		case v4[0] >= 240:
+			return true
+		}
+		return false
+	}
+	if len(ip) == net.IPv6len {
+		// 2001:db8::/32 (documentation) and 64:ff9b::/96 / 64:ff9b:1::/48
+		// (NAT64, which can map private IPv4 addresses).
+		if ip[0] == 0x20 && ip[1] == 0x01 && ip[2] == 0x0d && ip[3] == 0xb8 {
+			return true
+		}
+		if ip[0] == 0x00 && ip[1] == 0x64 && ip[2] == 0xff && ip[3] == 0x9b {
+			return true
+		}
+	}
+	return false
+}
+
+func resolvePushHost(ctx context.Context, host string) ([]net.IP, error) {
+	if ip := net.ParseIP(host); ip != nil {
+		return []net.IP{ip}, nil
+	}
+	addrs, err := net.DefaultResolver.LookupIPAddr(ctx, host)
+	if err != nil {
+		return nil, fmt.Errorf("resolver %s: %w", host, err)
+	}
+	ips := make([]net.IP, 0, len(addrs))
+	for _, addr := range addrs {
+		ips = append(ips, addr.IP)
+	}
+	if len(ips) == 0 {
+		return nil, fmt.Errorf("resolver %s: sin direcciones", host)
+	}
+	return ips, nil
+}
+
+func safeDialContext(ctx context.Context, network, addr string) (net.Conn, error) {
+	host, port, err := net.SplitHostPort(addr)
+	if err != nil {
+		return nil, fmt.Errorf("direccion de push invalida: %w", err)
+	}
+	ips, err := resolvePushHost(ctx, host)
+	if err != nil {
+		return nil, err
+	}
+	dialer := &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}
+	var lastErr error
+	for _, ip := range ips {
+		if blockedIP(ip) {
+			continue
+		}
+		conn, err := dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
+		if err == nil {
+			return conn, nil
+		}
+		lastErr = err
+	}
+	if lastErr != nil {
+		return nil, fmt.Errorf("conectar con %s: %w", host, lastErr)
+	}
+	return nil, fmt.Errorf("el endpoint %s resuelve a una direccion no publica", host)
+}
+
+func newSafeHTTPClient() *http.Client {
+	return &http.Client{
+		Timeout: sendTimeout,
+		Transport: &http.Transport{
+			Proxy:               nil,
+			DialContext:         safeDialContext,
+			ForceAttemptHTTP2:   true,
+			TLSHandshakeTimeout: 10 * time.Second,
+			MaxIdleConns:        20,
+			IdleConnTimeout:     90 * time.Second,
+			TLSClientConfig:     &tls.Config{MinVersion: tls.VersionTLS12},
+		},
+		CheckRedirect: func(req *http.Request, via []*http.Request) error {
+			if len(via) >= maxRedirects {
+				return errors.New("demasiadas redirecciones")
+			}
+			return ValidateEndpoint(req.URL.String())
+		},
+	}
+}

+ 52 - 0
server-go/internal/push/endpoint_internal_test.go

@@ -0,0 +1,52 @@
+package push
+
+import (
+	"context"
+	"net"
+	"net/http"
+	"testing"
+	"time"
+)
+
+func TestBlockedIP(t *testing.T) {
+	blocked := []string{
+		"127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.1.1", "169.254.169.254",
+		"100.64.0.1", "198.18.0.1", "192.0.2.1", "198.51.100.1", "203.0.113.1",
+		"240.0.0.1", "0.0.0.0", "::1", "fc00::1", "fe80::1", "2001:db8::1",
+		"64:ff9b::7f00:1",
+	}
+	for _, raw := range blocked {
+		ip := net.ParseIP(raw)
+		if ip == nil {
+			t.Fatalf("IP invalida en el test: %s", raw)
+		}
+		if !blockedIP(ip) {
+			t.Errorf("blockedIP(%s) = false, want true", raw)
+		}
+	}
+	for _, raw := range []string{"8.8.8.8", "1.1.1.1", "2001:4860:4860::8888"} {
+		ip := net.ParseIP(raw)
+		if blockedIP(ip) {
+			t.Errorf("blockedIP(%s) = true, want false", raw)
+		}
+	}
+}
+
+func TestSafeDialContextRejectsPrivateHost(t *testing.T) {
+	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+	defer cancel()
+	if _, err := safeDialContext(ctx, "tcp", "localhost:443"); err == nil {
+		t.Fatal("safeDialContext acepto localhost")
+	}
+}
+
+func TestSafeClientRejectsPrivateRedirect(t *testing.T) {
+	client := newSafeHTTPClient()
+	req, err := http.NewRequest(http.MethodGet, "https://127.0.0.1/x", nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if err := client.CheckRedirect(req, nil); err == nil {
+		t.Fatal("CheckRedirect acepto una redireccion a loopback")
+	}
+}

+ 84 - 0
server-go/internal/push/endpoint_test.go

@@ -0,0 +1,84 @@
+package push_test
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/push"
+)
+
+func TestValidateEndpoint(t *testing.T) {
+	valid := []string{
+		"https://push.example/abc",
+		"https://fcm.googleapis.com/wp/abc",
+		"https://8.8.8.8/x",
+		"https://[2001:4860:4860::8888]/x",
+		"https://push.example:8443/x",
+	}
+	for _, ep := range valid {
+		if err := push.ValidateEndpoint(ep); err != nil {
+			t.Errorf("ValidateEndpoint(%q) = %v, want nil", ep, err)
+		}
+	}
+
+	invalid := []string{
+		"",
+		"http://push.example/x",
+		"ftp://push.example/x",
+		"https:///x",
+		"https://user:pass@push.example/x",
+		"https://localhost/x",
+		"https://foo.localhost/x",
+		"https://127.0.0.1/x",
+		"https://[::1]/x",
+		"https://10.0.0.1/x",
+		"https://172.16.0.1/x",
+		"https://192.168.1.1/x",
+		"https://169.254.169.254/latest/meta-data",
+		"https://0.0.0.0/x",
+		"https://100.64.0.1/x",
+		"https://198.18.0.1/x",
+		"https://192.0.2.1/x",
+		"https://198.51.100.1/x",
+		"https://203.0.113.1/x",
+		"https://240.0.0.1/x",
+		"https://[::ffff:127.0.0.1]/x",
+		"https://[fc00::1]/x",
+		"https://[fe80::1]/x",
+		"https://[2001:db8::1]/x",
+		"https://[64:ff9b::7f00:1]/x",
+		"https://push.example:99999/x",
+	}
+	for _, ep := range invalid {
+		if err := push.ValidateEndpoint(ep); err == nil {
+			t.Errorf("ValidateEndpoint(%q) = nil, want error", ep)
+		}
+	}
+}
+
+func TestNotifierSkipsPrivateEndpoint(t *testing.T) {
+	d, _ := openDB(t)
+	ua := newBrowserSub(t)
+	hit := make(chan struct{}, 1)
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		hit <- struct{}{}
+		w.WriteHeader(http.StatusCreated)
+	}))
+	defer srv.Close()
+
+	if _, err := push.UpsertSubscription(d, push.Subscription{
+		Endpoint: srv.URL, Auth: ua.authB, P256dh: ua.pubB,
+	}); err != nil {
+		t.Fatalf("upsert: %v", err)
+	}
+
+	n := newNotifier(t, d)
+	n.Notify(testEvent())
+	select {
+	case <-hit:
+		t.Fatal("el notifier alcanzo un endpoint http de loopback")
+	case <-time.After(500 * time.Millisecond):
+	}
+}

+ 18 - 1
server-go/internal/push/notifier.go

@@ -68,11 +68,24 @@ type Notifier struct {
 // NewNotifier crea el Notifier y arranca su worker. pub/priv son el par
 // VAPID de EnsureVAPIDKeys.
 func NewNotifier(d *db.DB, pub, priv string) *Notifier {
+	return newNotifier(d, pub, priv, newSafeHTTPClient())
+}
+
+// NewNotifierWithClient permite inyectar un cliente HTTP. Se usa en tests que
+// necesitan alcanzar un push service TLS local; produccion usa NewNotifier.
+func NewNotifierWithClient(d *db.DB, pub, priv string, client *http.Client) *Notifier {
+	if client == nil {
+		client = newSafeHTTPClient()
+	}
+	return newNotifier(d, pub, priv, client)
+}
+
+func newNotifier(d *db.DB, pub, priv string, client *http.Client) *Notifier {
 	n := &Notifier{
 		db:     d,
 		pub:    pub,
 		priv:   priv,
-		client: &http.Client{Timeout: sendTimeout},
+		client: client,
 		ch:     make(chan alerts.AlertEvent, queueCap),
 		done:   make(chan struct{}),
 	}
@@ -155,6 +168,10 @@ func (n *Notifier) sendAll(ev alerts.AlertEvent) {
 }
 
 func (n *Notifier) sendOne(ev alerts.AlertEvent, body []byte, s Subscription) {
+	if err := ValidateEndpoint(s.Endpoint); err != nil {
+		slog.Warn("push: endpoint rechazado", "endpoint", s.Endpoint, "error", err)
+		return
+	}
 	resp, err := webpush.SendNotificationWithContext(context.Background(), body,
 		&webpush.Subscription{
 			Endpoint: s.Endpoint,

+ 39 - 18
server-go/internal/push/push_test.go

@@ -5,15 +5,18 @@
 package push_test
 
 import (
+	"context"
 	"crypto/aes"
 	"crypto/cipher"
 	"crypto/elliptic"
 	"crypto/rand"
 	"crypto/sha256"
+	"crypto/tls"
 	"encoding/base64"
 	"encoding/binary"
 	"encoding/json"
 	"io"
+	"net"
 	"net/http"
 	"net/http/httptest"
 	"os"
@@ -212,17 +215,36 @@ func testEvent() alerts.AlertEvent {
 	}
 }
 
-func newNotifier(t *testing.T, d *db.DB) *push.Notifier {
+func newNotifier(t *testing.T, d *db.DB, clients ...*http.Client) *push.Notifier {
 	t.Helper()
 	pub, priv, err := push.EnsureVAPIDKeys(d)
 	if err != nil {
 		t.Fatalf("vapid: %v", err)
 	}
-	n := push.NewNotifier(d, pub, priv)
+	var n *push.Notifier
+	if len(clients) > 0 && clients[0] != nil {
+		n = push.NewNotifierWithClient(d, pub, priv, clients[0])
+	} else {
+		n = push.NewNotifier(d, pub, priv)
+	}
 	t.Cleanup(n.Close)
 	return n
 }
 
+// testPushClient routes every request to the given test TLS server, so tests
+// can use public-looking endpoints such as https://push.example.
+func testPushClient(srv *httptest.Server) *http.Client {
+	return &http.Client{
+		Timeout: 15 * time.Second,
+		Transport: &http.Transport{
+			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
+			DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
+				return (&net.Dialer{}).DialContext(ctx, network, srv.Listener.Addr().String())
+			},
+		},
+	}
+}
+
 // El Notifier envía un POST cifrado aes128gcm con cabecera VAPID al endpoint
 // suscrito, y el payload descifrado cumple el contrato del SW.
 func TestNotifierSendsEncryptedPayload(t *testing.T) {
@@ -231,7 +253,7 @@ func TestNotifierSendsEncryptedPayload(t *testing.T) {
 	ua := newBrowserSub(t)
 
 	got := make(chan capturedPush, 1)
-	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		body, _ := io.ReadAll(r.Body)
 		got <- capturedPush{method: r.Method, header: r.Header.Clone(), body: body}
 		w.WriteHeader(http.StatusCreated)
@@ -239,12 +261,12 @@ func TestNotifierSendsEncryptedPayload(t *testing.T) {
 	defer srv.Close()
 
 	if _, err := push.UpsertSubscription(d, push.Subscription{
-		Endpoint: srv.URL, Auth: ua.authB, P256dh: ua.pubB,
+		Endpoint: "https://push.example/send", Auth: ua.authB, P256dh: ua.pubB,
 	}); err != nil {
 		t.Fatalf("upsert: %v", err)
 	}
 
-	n := newNotifier(t, d)
+	n := newNotifier(t, d, testPushClient(srv))
 	n.Notify(testEvent())
 
 	var req capturedPush
@@ -306,24 +328,23 @@ func TestNotifierPurgesGoneSubscription(t *testing.T) {
 	ua := newBrowserSub(t)
 
 	got := make(chan struct{}, 2)
-	dead := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
-		got <- struct{}{}
-		w.WriteHeader(http.StatusGone)
-	}))
-	defer dead.Close()
-	alive := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		got <- struct{}{}
+		if r.URL.Path == "/dead" {
+			w.WriteHeader(http.StatusGone)
+			return
+		}
 		w.WriteHeader(http.StatusCreated)
 	}))
-	defer alive.Close()
+	defer srv.Close()
 
-	for _, ep := range []string{dead.URL, alive.URL} {
+	for _, ep := range []string{"https://push.example/dead", "https://push.example/alive"} {
 		if _, err := push.UpsertSubscription(d, push.Subscription{Endpoint: ep, Auth: ua.authB, P256dh: ua.pubB}); err != nil {
 			t.Fatalf("upsert: %v", err)
 		}
 	}
 
-	n := newNotifier(t, d)
+	n := newNotifier(t, d, testPushClient(srv))
 	n.Notify(testEvent())
 	for i := 0; i < 2; i++ {
 		select {
@@ -338,7 +359,7 @@ func TestNotifierPurgesGoneSubscription(t *testing.T) {
 	if err != nil {
 		t.Fatalf("list: %v", err)
 	}
-	if len(subs) != 1 || subs[0].Endpoint != alive.URL {
+	if len(subs) != 1 || subs[0].Endpoint != "https://push.example/alive" {
 		t.Fatalf("tras purga: %+v", subs)
 	}
 }
@@ -394,7 +415,7 @@ func TestNotifierLocalizesPerSubscription(t *testing.T) {
 		body []byte
 	}
 	ch := make(chan got, 2)
-	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		body, _ := io.ReadAll(r.Body)
 		ch <- got{path: r.URL.Path, body: body}
 		w.WriteHeader(http.StatusCreated)
@@ -409,13 +430,13 @@ func TestNotifierLocalizesPerSubscription(t *testing.T) {
 		{"/en", "en", uaEN},
 	} {
 		if _, err := push.UpsertSubscription(d, push.Subscription{
-			Endpoint: srv.URL + s.path, Auth: s.ua.authB, P256dh: s.ua.pubB, Language: s.lang,
+			Endpoint: "https://push.example" + s.path, Auth: s.ua.authB, P256dh: s.ua.pubB, Language: s.lang,
 		}); err != nil {
 			t.Fatalf("upsert: %v", err)
 		}
 	}
 
-	n := newNotifier(t, d)
+	n := newNotifier(t, d, testPushClient(srv))
 	n.Notify(alerts.AlertEvent{
 		ID: "alert-agent-down-gateway", Category: alerts.CatRouter, Urgent: true, Severity: "warn",
 		Type: "agent-down", Title: "CANARY", Description: "CANARY",