fix(ddns): apply SSRF defense to webhook provider

GHSA-6x26-5727-rrm9: a low-privilege member could point a DDNS webhook
at internal or loopback hosts and the dashboard would dial them with the
unrestricted utils.HttpClient.

Extract the notification SSRF defenses (CIDR blocklist, IP-pin DialContext,
SNI preservation, redirect rejection) into reusable helpers in pkg/utils
(NewRestrictedHTTPClient / ResolveAllowedHTTPURL / buildRestrictedHTTPClient)
and route the DDNS webhook through the same path. Replace the notification
inline implementation with a thin wrapper to keep behaviour identical.

Side improvements collected by the refactor:
- prepareRequest now resolves DNS once and returns the paired client, so
  the dialer's pinned IP and the validated URL stay in sync (no more
  double resolution between prepareRequest and SetRecords).
- response body is drained and closed.
- HttpClient / HttpClientSkipTlsVerify are explicitly tagged unsafe for
  attacker-controlled URLs.

Tests cover: hermetic SNI preservation, redirect rejection, dial pin to
the vetted IP, the full blocked-CIDR list at the webhook entry point,
and the verifyTLS↔skipVerifyTLS inversion in the notification wrapper.

Co-authored-by: naiba/CloudCode <hi+cloudcode@nai.ba>
This commit is contained in:
naiba
2026-05-18 15:14:27 +00:00
co-authored by naiba/CloudCode
parent 05e5da2535
commit e7c2e453c0
6 changed files with 370 additions and 169 deletions
+2 -127
View File
@@ -1,14 +1,10 @@
package model
import (
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/netip"
"net/url"
"strings"
"time"
@@ -29,35 +25,6 @@ const (
NotificationRequestMethodPOST
)
var errNotificationURLNotAllowed = errors.New("notification URL target is not allowed")
var notificationBlockedCIDRs = mustParseNotificationCIDRs([]string{
"0.0.0.0/8",
"10.0.0.0/8",
"100.64.0.0/10",
"127.0.0.0/8",
"169.254.0.0/16",
"172.16.0.0/12",
"192.0.0.0/24",
"192.0.2.0/24",
"192.168.0.0/16",
"198.18.0.0/15",
"198.51.100.0/24",
"203.0.113.0/24",
"224.0.0.0/4",
"240.0.0.0/4",
"::/128",
"::1/128",
"::ffff:0:0/96",
"64:ff9b::/96",
"100::/64",
"2001::/23",
"2001:db8::/32",
"fc00::/7",
"fe80::/10",
"ff00::/8",
})
type NotificationServerBundle struct {
Notification *Notification
Server *Server
@@ -191,105 +158,13 @@ func (ns *NotificationServerBundle) Send(message string) error {
return nil
}
func newNotificationHTTPClient(rawURL string, verifyTLS bool) (*http.Client, error) {
parsedURL, ip, err := resolveNotificationTarget(rawURL)
if err != nil {
return nil, err
}
port := parsedURL.Port()
if port == "" {
if parsedURL.Scheme == "https" {
port = "443"
} else {
port = "80"
}
}
targetAddress := net.JoinHostPort(ip.String(), port)
dialer := &net.Dialer{}
return &http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
return dialer.DialContext(ctx, network, targetAddress)
},
TLSClientConfig: &tls.Config{InsecureSkipVerify: !verifyTLS, ServerName: parsedURL.Hostname()},
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Timeout: time.Minute * 10,
}, nil
}
func notificationResponseError(resp *http.Response) error {
_, _ = io.CopyN(io.Discard, resp.Body, 4096)
return fmt.Errorf("%d@%s", resp.StatusCode, resp.Status)
}
func resolveNotificationTarget(rawURL string) (*url.URL, net.IP, error) {
parsedURL, err := url.Parse(rawURL)
if err != nil {
return nil, nil, err
}
if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" {
return nil, nil, errNotificationURLNotAllowed
}
host := parsedURL.Hostname()
if host == "" {
return nil, nil, errNotificationURLNotAllowed
}
if ip := net.ParseIP(host); ip != nil {
if !notificationIPAllowed(ip) {
return nil, nil, errNotificationURLNotAllowed
}
return parsedURL, ip, nil
}
ips, err := net.LookupIP(host)
if err != nil {
return nil, nil, err
}
if len(ips) == 0 {
return nil, nil, errNotificationURLNotAllowed
}
for _, ip := range ips {
if !notificationIPAllowed(ip) {
return nil, nil, errNotificationURLNotAllowed
}
}
return parsedURL, ips[0], nil
}
func notificationIPAllowed(ip net.IP) bool {
parsedIP, ok := netipFromIP(ip)
if !ok {
return false
}
for _, cidr := range notificationBlockedCIDRs {
if cidr.Contains(parsedIP) {
return false
}
}
return parsedIP.IsGlobalUnicast()
}
func netipFromIP(ip net.IP) (netip.Addr, bool) {
parsedIP, ok := netip.AddrFromSlice(ip)
if !ok {
return netip.Addr{}, false
}
return parsedIP.Unmap(), true
}
func mustParseNotificationCIDRs(cidrs []string) []netip.Prefix {
prefixes := make([]netip.Prefix, 0, len(cidrs))
for _, cidr := range cidrs {
prefixes = append(prefixes, netip.MustParsePrefix(cidr))
}
return prefixes
func newNotificationHTTPClient(rawURL string, verifyTLS bool) (*http.Client, error) {
return utils.NewRestrictedHTTPClient(rawURL, !verifyTLS)
}
// replaceParamInString 替换字符串中的占位符
+34 -27
View File
@@ -6,6 +6,8 @@ import (
"strings"
"testing"
"time"
"github.com/nezhahq/nezha/pkg/utils"
)
var (
@@ -307,7 +309,7 @@ func TestNotificationTargetRejectsBlockedRanges(t *testing.T) {
for _, rawURL := range cases {
t.Run(rawURL, func(t *testing.T) {
if _, _, err := resolveNotificationTarget(rawURL); err == nil {
if _, _, err := utils.ResolveAllowedHTTPURL(rawURL); err == nil {
t.Fatalf("expected %s to be rejected", rawURL)
}
})
@@ -323,7 +325,7 @@ func TestNotificationTargetAllowsPublicAddresses(t *testing.T) {
for _, rawURL := range cases {
t.Run(rawURL, func(t *testing.T) {
parsedURL, _, err := resolveNotificationTarget(rawURL)
parsedURL, _, err := utils.ResolveAllowedHTTPURL(rawURL)
if err != nil {
t.Fatalf("expected %s to be allowed, got %v", rawURL, err)
}
@@ -334,31 +336,36 @@ func TestNotificationTargetAllowsPublicAddresses(t *testing.T) {
}
}
func TestNotificationHTTPClientPreservesTLSServerName(t *testing.T) {
client, err := newNotificationHTTPClient("https://1.1.1.1/webhook", true)
if err != nil {
t.Fatalf("expected public HTTPS URL to create client: %v", err)
func TestNotificationHTTPClientInvertsVerifyTLSFlag(t *testing.T) {
// newNotificationHTTPClient takes verifyTLS, utils.NewRestrictedHTTPClient
// takes skipVerifyTLS. The wrapper must invert the boolean; if a future
// refactor drops the negation, TLS verification silently turns off.
// SNI / redirect / IP-pinning are covered by pkg/utils/http_test.go.
cases := []struct {
name string
verifyTLS bool
wantSkipVerifyOn bool
}{
{"verifyTLS_true_means_skipVerify_false", true, false},
{"verifyTLS_false_means_skipVerify_true", false, true},
}
transport, ok := client.Transport.(*http.Transport)
if !ok {
t.Fatalf("expected http.Transport, got %T", client.Transport)
}
if transport.TLSClientConfig == nil || transport.TLSClientConfig.ServerName != "1.1.1.1" {
t.Fatalf("expected TLS ServerName 1.1.1.1, got %#v", transport.TLSClientConfig)
}
}
func TestNotificationHTTPClientRejectsRedirects(t *testing.T) {
client, err := newNotificationHTTPClient("https://1.1.1.1/webhook", true)
if err != nil {
t.Fatalf("expected client construction: %v", err)
}
req, err := http.NewRequest(http.MethodGet, "https://1.1.1.1/start", nil)
if err != nil {
t.Fatalf("new request: %v", err)
}
via := []*http.Request{req}
if err := client.CheckRedirect(req, via); err != http.ErrUseLastResponse {
t.Fatalf("expected ErrUseLastResponse, got %v", err)
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
client, err := newNotificationHTTPClient("https://1.1.1.1/webhook", tc.verifyTLS)
if err != nil {
t.Fatalf("expected client construction: %v", err)
}
transport, ok := client.Transport.(*http.Transport)
if !ok {
t.Fatalf("expected *http.Transport, got %T", client.Transport)
}
if transport.TLSClientConfig == nil {
t.Fatalf("expected TLSClientConfig to be set")
}
if got := transport.TLSClientConfig.InsecureSkipVerify; got != tc.wantSkipVerifyOn {
t.Fatalf("verifyTLS=%v: expected InsecureSkipVerify=%v, got %v",
tc.verifyTLS, tc.wantSkipVerifyOn, got)
}
})
}
}