From c8935102c33c306e5ac6c1a2472544fd3bff0015 Mon Sep 17 00:00:00 2001 From: yusing Date: Sat, 29 Mar 2025 02:53:41 +0800 Subject: [PATCH] feat: add validation for localhost routes to prevent usage of godoxy port causing self recursion --- internal/common/env.go | 6 +++++- internal/net/gphttp/middleware/redirect_http.go | 5 +++-- internal/route/route.go | 11 +++++++++++ 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/internal/common/env.go b/internal/common/env.go index 9df4cb7..c73028b 100644 --- a/internal/common/env.go +++ b/internal/common/env.go @@ -95,7 +95,7 @@ func GetEnvInt(key string, defaultValue int) int { return GetEnv(key, defaultValue, strconv.Atoi) } -func GetAddrEnv(key, defaultValue, scheme string) (addr, host, port, fullURL string) { +func GetAddrEnv(key, defaultValue, scheme string) (addr, host string, portInt int, fullURL string) { addr = GetEnvString(key, defaultValue) if addr == "" { return @@ -108,6 +108,10 @@ func GetAddrEnv(key, defaultValue, scheme string) (addr, host, port, fullURL str host = "localhost" } fullURL = fmt.Sprintf("%s://%s:%s", scheme, host, port) + portInt, err = strconv.Atoi(port) + if err != nil { + log.Fatal().Msgf("env %s: invalid port: %s", key, port) + } return } diff --git a/internal/net/gphttp/middleware/redirect_http.go b/internal/net/gphttp/middleware/redirect_http.go index 26ec2cc..7f6c6d3 100644 --- a/internal/net/gphttp/middleware/redirect_http.go +++ b/internal/net/gphttp/middleware/redirect_http.go @@ -3,6 +3,7 @@ package middleware import ( "net" "net/http" + "strconv" "strings" "github.com/yusing/go-proxy/internal/common" @@ -38,8 +39,8 @@ func (m *redirectHTTP) before(w http.ResponseWriter, r *http.Request) (proceed b host = r.Host } - if common.ProxyHTTPSPort != "443" { - r.URL.Host = host + ":" + common.ProxyHTTPSPort + if common.ProxyHTTPSPort != 443 { + r.URL.Host = host + ":" + strconv.Itoa(common.ProxyHTTPSPort) } else { r.URL.Host = host } diff --git a/internal/route/route.go b/internal/route/route.go index 0f99680..43cfa9d 100644 --- a/internal/route/route.go +++ b/internal/route/route.go @@ -75,6 +75,17 @@ func (r *Route) Validate() (err gperr.Error) { r.isValidated = true r.Finalize() + // return error if route is localhost: + switch r.Host { + case "localhost", "127.0.0.1": + switch r.Port.Proxy { + case common.ProxyHTTPPort, common.ProxyHTTPSPort, common.APIHTTPPort: + if r.Scheme.IsReverseProxy() || r.Scheme == types.SchemeTCP { + return gperr.Errorf("localhost:%d is reserved for godoxy", r.Port.Proxy) + } + } + } + errs := gperr.NewBuilder("entry validation failed") switch r.Scheme {