Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions forwardproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -533,15 +533,32 @@ match:

// This is net.Dial's default behavior: if the host resolves to multiple IP addresses,
// Dial will try each IP address in order until one succeeds

var lastDialErr error
var hadAllowedIP bool

for _, ip := range IPs {
if !h.hostIsAllowed(host, ip) {
continue
}

hadAllowedIP = true

conn, err = h.dialContext(ctx, network, net.JoinHostPort(ip.String(), port))
if err == nil {
return conn, nil
}

lastDialErr = err
}

// If at least one IP address was permitted by ACL but dialing all of them failed,
// return Bad Gateway. Otherwise the host did not have any allowed IPs and is forbidden.
if hadAllowedIP {
return nil, caddyhttp.Error(
http.StatusBadGateway,
fmt.Errorf("failed to connect to %s after trying allowed IP addresses: %v", host, lastDialErr),
)
}

return nil, caddyhttp.Error(http.StatusForbidden, fmt.Errorf("no allowed IP addresses for %s", host))
Expand Down
13 changes: 13 additions & 0 deletions forwardproxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,19 @@ func TestGETNoAuth(t *testing.T) {
}
}

func TestGETAllowedIPDialFailureReturnsBadGateway(t *testing.T) {
const useTLS = true
for _, httpProxyVer := range testHTTPProxyVersions {
response, err := getViaProxy("198.51.100.1:12345", "/", caddyForwardProxy.addr, httpProxyVer, credentialsEmpty, useTLS)
if err != nil {
t.Fatal(err)
}
if response.StatusCode != http.StatusBadGateway {
t.Fatalf("Expected response 502 StatusBadGateway for allowed host with dial failure, got %d", response.StatusCode)
}
}
}

func TestGETAuthCorrect(t *testing.T) {
const useTLS = true
for _, httpProxyVer := range testHTTPProxyVersions {
Expand Down