From 59b95ea31523bd80763be7cbc816b34cb7dea8db Mon Sep 17 00:00:00 2001 From: Adrien PONSIN Date: Thu, 17 Apr 2025 21:46:41 +0200 Subject: [PATCH] improve default regex --- command/serve.go | 84 ++++---------------------------------------- pkg/fastrp/fastrp.go | 1 - 2 files changed, 7 insertions(+), 78 deletions(-) diff --git a/command/serve.go b/command/serve.go index 694b73f..3a7c010 100644 --- a/command/serve.go +++ b/command/serve.go @@ -12,7 +12,6 @@ import ( "golang.org/x/sync/errgroup" "net" "net/http" - "net/http/httputil" "net/netip" "net/url" "regexp" @@ -34,11 +33,6 @@ type addrPorts struct { // methodRegex maps HTTP methods (GET, POST, DELETE...) to a compiled regular expression. type methodRegex = map[string]*regexp.Regexp -// ProxyHandlerOld takes an incoming request and sends it to another server, proxying the response back to the client. -type ProxyHandlerOld struct { - rp *httputil.ReverseProxy -} - // ProxyHandler takes an incoming request and sends it to another server, proxying the response back to the client. type ProxyHandler struct { frp *fastrp.FastRP @@ -81,8 +75,8 @@ const ( defaultHealthEndpoint = "/healthz" // defaultHealthListenAddr is the proxy health endpoint default listen address and port. defaultHealthListenAddr = "127.0.0.1:5732" - // defaultAllowedRequest is the proxy default allowed request. - defaultAllowedRequest = "^/(version|containers/.*|events.*)$" + // defaultAllowedRequests is the default allowed requests. Note that they should be sufficient to make Traefik work properly. + defaultAllowedRequests = "/v1.\\d{1,2}/(version|containers/(?:json|[a-zA-Z0-9]{64}/json)|events)$" ) var s serve @@ -90,7 +84,7 @@ var s serve var ( containerMethodRegex = map[string]methodRegex{ "*": { - http.MethodGet: regexp.MustCompile(defaultAllowedRequest), + http.MethodGet: regexp.MustCompile(defaultAllowedRequests), }, } applicatorURLRegex = regexp.MustCompile(`^([a-zA-Z0-9][a-zA-Z0-9_.-]+)\(((?:(?:GET|HEAD|POST|PUT|PATCH|DELETE|CONNECT|TRACE|OPTIONS)(?:,(?:GET|HEAD|POST|PUT|PATCH|DELETE|CONNECT|TRACE|OPTIONS))*)?)\):(.*)$`) @@ -161,44 +155,6 @@ func (ph *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) } -func (ph *ProxyHandlerOld) ServeHTTP(w http.ResponseWriter, r *http.Request) { - log.Debug().Str("remote_addr", r.RemoteAddr).Str("method", r.Method).Str("path", r.URL.Path).Msg("incoming request") - if mr, ok := containerMethodRegex["*"]; ok { - if code := ph.checkMethodAndRegex(mr, r, ""); code != http.StatusOK { - http.Error(w, http.StatusText(code), code) - return - } - ph.rp.ServeHTTP(w, r) - return - } - host, _, _ := net.SplitHostPort(r.RemoteAddr) - for containerName, mr := range containerMethodRegex { - if ph.isContainerAuthorized(containerName, host) { - if code := ph.checkMethodAndRegex(mr, r, containerName); code != http.StatusOK { - http.Error(w, http.StatusText(code), code) - return - } - ph.rp.ServeHTTP(w, r) - return - } - } - logDeniedRequest(r, http.StatusUnauthorized, "this container is not on the list of authorized ones") - http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) -} - -func (ph *ProxyHandlerOld) isContainerAuthorized(containerName, host string) bool { - resolvedIPs, err := net.LookupIP(containerName) - if err != nil { - return false - } - for resolvedIP := range slices.Values(resolvedIPs) { - if resolvedIP.Equal(net.ParseIP(host)) { - return true - } - } - return false -} - func (ph *ProxyHandler) isContainerAuthorized(containerName, host string) bool { resolvedIPs, err := net.LookupIP(containerName) if err != nil { @@ -232,20 +188,6 @@ func logAuthorizedRequest(r *http.Request, containerName, message string) { l.Msg(message) } -func (ph *ProxyHandlerOld) checkMethodAndRegex(mr methodRegex, r *http.Request, containerName string) int { - req, ok := mr[r.Method] - if !ok { - logDeniedRequest(r, http.StatusMethodNotAllowed, "this HTTP method is not in the list of those authorized for this container") - return http.StatusMethodNotAllowed - } - if !req.MatchString(r.URL.Path) { - logDeniedRequest(r, http.StatusForbidden, "this path does not match any regular expression for this HTTP method") - return http.StatusForbidden - } - logAuthorizedRequest(r, containerName, "incoming request matches a registered regular expression") - return http.StatusOK -} - func (ph *ProxyHandler) checkMethodAndRegex(mr methodRegex, r *http.Request, containerName string) int { req, ok := mr[r.Method] if !ok { @@ -275,23 +217,11 @@ func (s serve) action(ctx context.Context, command *cli.Command) error { return err } dummyURL, _ := url.Parse("http://dummy") - - // Old - // rp := httputil.NewSingleHostReverseProxy(dummyURL) - // rp.Transport = &http.Transport{ - // DialContext: func(_ context.Context, _ string, _ string) (net.Conn, error) { - // return net.Dial("unix", command.String(dockerSocketPathFlagName)) - // }, - // } - - // New - rp := fastrp.NewRP("unix", command.String(dockerSocketPathFlagName), dummyURL) - srv := &http.Server{ // #nosec: G112 - // Handler: &ProxyHandlerOld{rp: rp}, - Handler: &ProxyHandler{frp: rp}, + Handler: &ProxyHandler{ + frp: fastrp.NewRP("unix", command.String(dockerSocketPathFlagName), dummyURL), + }, } - s.group.Go(func() error { if err = srv.Serve(l); err != nil && !errors.Is(err, http.ErrServerClosed) { return err @@ -489,7 +419,7 @@ func addRequests() cli.Flag { Usage: "add requests", Sources: middleman.PluckEnvVar(EnvVarPrefix, addRequestsFlagName), // Local: true, // Required to trigger the Action when this flag is set via the environment variable, see https://github.com/urfave/cli/issues/2041. - Value: []string{"*:" + defaultAllowedRequest}, + Value: []string{"*:" + defaultAllowedRequests}, Aliases: middleman.PluckAlias(ServeCmd, addRequestsFlagName), Action: func(ctx context.Context, command *cli.Command, requests []string) error { clear(containerMethodRegex) diff --git a/pkg/fastrp/fastrp.go b/pkg/fastrp/fastrp.go index 9285187..2709317 100644 --- a/pkg/fastrp/fastrp.go +++ b/pkg/fastrp/fastrp.go @@ -9,7 +9,6 @@ import ( "sync" ) -// FastRP takes an incoming request and sends it fast to another server, proxying the response back to the client fast. type FastRP struct { rp *httputil.ReverseProxy connPool *sync.Pool