Compare commits
20 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
59b95ea315 | ||
![]() |
fcaafbf3f4 | ||
![]() |
c55dec6bc4 | ||
![]() |
17aa156fa5 | ||
![]() |
7bc9fa242e | ||
![]() |
3937b7cda5 | ||
![]() |
52b4d44b4b | ||
![]() |
6a1c6c5967 | ||
![]() |
ec887ccb93 | ||
![]() |
3829a46f87 | ||
![]() |
47538621c9 | ||
![]() |
8adf4be96e | ||
![]() |
90d442b611 | ||
![]() |
c76d7b4d12 | ||
![]() |
7aef361ed2 | ||
![]() |
17c73fb900 | ||
![]() |
b373dd004e | ||
![]() |
24316804d9 | ||
![]() |
32306467ea | ||
![]() |
7c99754d5a |
@ -37,10 +37,9 @@ func main() {
|
|||||||
var group *errgroup.Group
|
var group *errgroup.Group
|
||||||
group, ctx = errgroup.WithContext(ctx)
|
group, ctx = errgroup.WithContext(ctx)
|
||||||
app := cli.Command{
|
app := cli.Command{
|
||||||
Name: appName,
|
Name: appName,
|
||||||
Usage: "Securely mount the Docker socket: apply fine-grained access control to Docker socket HTTP requests",
|
Usage: "Securely mount the Docker socket: apply fine-grained access control to Docker socket HTTP requests",
|
||||||
Version: buildVersion(),
|
Version: buildVersion(),
|
||||||
DefaultCommand: command.ServeCmd,
|
|
||||||
Commands: []*cli.Command{
|
Commands: []*cli.Command{
|
||||||
command.Serve(group),
|
command.Serve(group),
|
||||||
command.Healthcheck(group),
|
command.Healthcheck(group),
|
||||||
|
177
command/serve.go
177
command/serve.go
@ -6,15 +6,16 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"gitea.illuad.fr/adrien/middleman"
|
"gitea.illuad.fr/adrien/middleman"
|
||||||
"gitea.illuad.fr/adrien/middleman/flag"
|
"gitea.illuad.fr/adrien/middleman/flag"
|
||||||
|
"gitea.illuad.fr/adrien/middleman/pkg/fastrp"
|
||||||
"github.com/rs/zerolog/log"
|
"github.com/rs/zerolog/log"
|
||||||
"github.com/urfave/cli/v3"
|
"github.com/urfave/cli/v3"
|
||||||
"golang.org/x/sync/errgroup"
|
"golang.org/x/sync/errgroup"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httputil"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"net/url"
|
"net/url"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@ -34,25 +35,7 @@ type methodRegex = map[string]*regexp.Regexp
|
|||||||
|
|
||||||
// ProxyHandler takes an incoming request and sends it to another server, proxying the response back to the client.
|
// ProxyHandler takes an incoming request and sends it to another server, proxying the response back to the client.
|
||||||
type ProxyHandler struct {
|
type ProxyHandler struct {
|
||||||
rp *httputil.ReverseProxy
|
frp *fastrp.FastRP
|
||||||
}
|
|
||||||
|
|
||||||
// ErrHTTPMethodNotAllowed is returned if the request's HTTP method is not allowed for this container.
|
|
||||||
type ErrHTTPMethodNotAllowed struct {
|
|
||||||
httpMethod string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ErrNoMatch is returned if the request's URL path is not allowed for this container.
|
|
||||||
type ErrNoMatch struct {
|
|
||||||
path, httpMethod string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e ErrHTTPMethodNotAllowed) Error() string {
|
|
||||||
return fmt.Sprintf("%s is not in the list of HTTP methods allowed this container", e.httpMethod)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e ErrNoMatch) Error() string {
|
|
||||||
return fmt.Sprintf("%s does not match any registered regular expression for this HTTP method (%s)", e.path, e.httpMethod)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ServeCmd is the command name.
|
// ServeCmd is the command name.
|
||||||
@ -92,8 +75,8 @@ const (
|
|||||||
defaultHealthEndpoint = "/healthz"
|
defaultHealthEndpoint = "/healthz"
|
||||||
// defaultHealthListenAddr is the proxy health endpoint default listen address and port.
|
// defaultHealthListenAddr is the proxy health endpoint default listen address and port.
|
||||||
defaultHealthListenAddr = "127.0.0.1:5732"
|
defaultHealthListenAddr = "127.0.0.1:5732"
|
||||||
// defaultAllowedRequest is the proxy default allowed request.
|
// defaultAllowedRequests is the default allowed requests. Note that they should be sufficient to make Traefik work properly.
|
||||||
defaultAllowedRequest = "^/(version|containers/.*|events.*)$"
|
defaultAllowedRequests = "/v1.\\d{1,2}/(version|containers/(?:json|[a-zA-Z0-9]{64}/json)|events)$"
|
||||||
)
|
)
|
||||||
|
|
||||||
var s serve
|
var s serve
|
||||||
@ -101,7 +84,7 @@ var s serve
|
|||||||
var (
|
var (
|
||||||
containerMethodRegex = map[string]methodRegex{
|
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))*)?)\):(.*)$`)
|
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))*)?)\):(.*)$`)
|
||||||
@ -148,56 +131,75 @@ func Serve(group *errgroup.Group) *cli.Command {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (ph *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (ph *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
log.Debug().Str("remote_addr", r.RemoteAddr).Str("http_method", r.Method).Str("path", r.URL.Path).Msg("incoming request")
|
log.Debug().Str("remote_addr", r.RemoteAddr).Str("method", r.Method).Str("path", r.URL.Path).Msg("incoming request")
|
||||||
mr, ok := containerMethodRegex["*"]
|
if mr, ok := containerMethodRegex["*"]; ok {
|
||||||
if ok {
|
if code := ph.checkMethodAndRegex(mr, r, ""); code != http.StatusOK {
|
||||||
if err := checkMethodPath(r, mr); err != nil {
|
http.Error(w, http.StatusText(code), code)
|
||||||
handleError(w, err)
|
|
||||||
log.Err(err).Send()
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
} else {
|
ph.frp.ServeHTTP(w, r)
|
||||||
var (
|
|
||||||
containerName string
|
|
||||||
host, _, _ = net.SplitHostPort(r.RemoteAddr)
|
|
||||||
ip = net.ParseIP(host)
|
|
||||||
)
|
|
||||||
for containerName, mr = range containerMethodRegex {
|
|
||||||
resolvedIPs, err := net.LookupIP(containerName)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
|
|
||||||
log.Err(err).Send()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for _, resolvedIP := range resolvedIPs {
|
|
||||||
log.Debug().Msgf("resolvedIP: %s -- IP: %s", resolvedIP.String(), ip.String())
|
|
||||||
if resolvedIP.Equal(ip) {
|
|
||||||
if err = checkMethodPath(r, mr); err != nil {
|
|
||||||
handleError(w, err)
|
|
||||||
log.Err(err).Send()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ph.rp.ServeHTTP(w, r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
|
|
||||||
return
|
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.frp.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)
|
||||||
}
|
}
|
||||||
|
|
||||||
// checkMethodPath executes the regular expression on the path of the HTTP request if and only if
|
func (ph *ProxyHandler) isContainerAuthorized(containerName, host string) bool {
|
||||||
// the latter's HTTP method is actually present in the list of authorized HTTP methods.
|
resolvedIPs, err := net.LookupIP(containerName)
|
||||||
func checkMethodPath(r *http.Request, mr methodRegex) error {
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for resolvedIP := range slices.Values(resolvedIPs) {
|
||||||
|
if resolvedIP.Equal(net.ParseIP(host)) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func logDeniedRequest(r *http.Request, statusCode int, message string) {
|
||||||
|
log.Error().
|
||||||
|
Str("remote_addr", r.RemoteAddr).Str("method", r.Method).
|
||||||
|
Str("path", r.URL.Path).Int("status_code", statusCode).
|
||||||
|
Str("status_text", http.StatusText(statusCode)).Msg(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
func logAuthorizedRequest(r *http.Request, containerName, message string) {
|
||||||
|
l := log.Info().
|
||||||
|
Str("remote_addr", r.RemoteAddr).
|
||||||
|
Str("method", r.Method).
|
||||||
|
Str("path", r.URL.Path).
|
||||||
|
Int("status_code", http.StatusOK).
|
||||||
|
Str("status_text", http.StatusText(http.StatusOK))
|
||||||
|
if containerName != "" {
|
||||||
|
l.Str("container_name", containerName)
|
||||||
|
}
|
||||||
|
l.Msg(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ph *ProxyHandler) checkMethodAndRegex(mr methodRegex, r *http.Request, containerName string) int {
|
||||||
req, ok := mr[r.Method]
|
req, ok := mr[r.Method]
|
||||||
if !ok {
|
if !ok {
|
||||||
return ErrHTTPMethodNotAllowed{httpMethod: r.Method}
|
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) {
|
if !req.MatchString(r.URL.Path) {
|
||||||
return ErrNoMatch{path: r.URL.Path, httpMethod: r.Method}
|
logDeniedRequest(r, http.StatusForbidden, "this path does not match any regular expression for this HTTP method")
|
||||||
|
return http.StatusForbidden
|
||||||
}
|
}
|
||||||
return nil
|
logAuthorizedRequest(r, containerName, "incoming request matches a registered regular expression")
|
||||||
|
return http.StatusOK
|
||||||
}
|
}
|
||||||
|
|
||||||
// action is executed when the ServeCmd command is called.
|
// action is executed when the ServeCmd command is called.
|
||||||
@ -209,47 +211,16 @@ func (s serve) action(ctx context.Context, command *cli.Command) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
/*
|
|
||||||
requests := command.StringSlice(addRequestsFlagName)
|
|
||||||
log.Info().Msgf("%d", len(requests))
|
|
||||||
if len(requests) > 0 {
|
|
||||||
clear(containerMethodRegex)
|
|
||||||
for _, request := range requests {
|
|
||||||
// An applicator is a container name/HTTP method pair e.g., nginx(GET).
|
|
||||||
// The following regex extracts this applicator and the associated URL regex.
|
|
||||||
aur := applicatorURLRegex.FindString(request)
|
|
||||||
if aur == "" {
|
|
||||||
// If we are here, it means that user set a wildcard (kinda) applicator e.g., GET,POST:URL_REGEX.
|
|
||||||
// In its extended form, this applicator can be read as follows: *(GET,POST):URL_REGEX.
|
|
||||||
methods, urlRegex, ok := strings.Cut(request, ":")
|
|
||||||
if !ok { // || methods == ""?
|
|
||||||
return errors.New("HTTP method(s) must be specified before ':'")
|
|
||||||
}
|
|
||||||
if err = registerMethodRegex("*", urlRegex, strings.Split(methods, ",")); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
applicator, urlRegex, _ := strings.Cut(aur, ":")
|
|
||||||
if err = registerMethodRegex(containerNameRegex.FindString(applicator), urlRegex, httpMethodsRegex.FindAllString(applicator, -1)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
var l net.Listener
|
var l net.Listener
|
||||||
l, err = net.Listen("tcp", ap.srvAddrPort.String())
|
l, err = net.Listen("tcp", ap.srvAddrPort.String())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
dummyURL, _ := url.Parse("http://dummy")
|
dummyURL, _ := url.Parse("http://dummy")
|
||||||
rp := httputil.NewSingleHostReverseProxy(dummyURL)
|
|
||||||
rp.Transport = &http.Transport{
|
|
||||||
DialContext: func(_ context.Context, _ string, _ string) (net.Conn, error) {
|
|
||||||
return net.Dial("unix", command.String(dockerSocketPathFlagName))
|
|
||||||
},
|
|
||||||
}
|
|
||||||
srv := &http.Server{ // #nosec: G112
|
srv := &http.Server{ // #nosec: G112
|
||||||
Handler: &ProxyHandler{rp: rp},
|
Handler: &ProxyHandler{
|
||||||
|
frp: fastrp.NewRP("unix", command.String(dockerSocketPathFlagName), dummyURL),
|
||||||
|
},
|
||||||
}
|
}
|
||||||
s.group.Go(func() error {
|
s.group.Go(func() error {
|
||||||
if err = srv.Serve(l); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
if err = srv.Serve(l); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||||
@ -448,7 +419,7 @@ func addRequests() cli.Flag {
|
|||||||
Usage: "add requests",
|
Usage: "add requests",
|
||||||
Sources: middleman.PluckEnvVar(EnvVarPrefix, addRequestsFlagName),
|
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.
|
// 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),
|
Aliases: middleman.PluckAlias(ServeCmd, addRequestsFlagName),
|
||||||
Action: func(ctx context.Context, command *cli.Command, requests []string) error {
|
Action: func(ctx context.Context, command *cli.Command, requests []string) error {
|
||||||
clear(containerMethodRegex)
|
clear(containerMethodRegex)
|
||||||
@ -493,15 +464,3 @@ func registerMethodRegex(containerName, urlRegex string, httpMethods []string) e
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleError(w http.ResponseWriter, err error) {
|
|
||||||
var methodNotAllowedErr ErrHTTPMethodNotAllowed
|
|
||||||
var noMatchErr ErrNoMatch
|
|
||||||
if errors.As(err, &methodNotAllowedErr) {
|
|
||||||
http.Error(w, err.Error(), http.StatusMethodNotAllowed)
|
|
||||||
} else if errors.As(err, &noMatchErr) {
|
|
||||||
http.Error(w, err.Error(), http.StatusForbidden)
|
|
||||||
} else {
|
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
41
pkg/fastrp/fastrp.go
Normal file
41
pkg/fastrp/fastrp.go
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
package fastrp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httputil"
|
||||||
|
"net/url"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FastRP struct {
|
||||||
|
rp *httputil.ReverseProxy
|
||||||
|
connPool *sync.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRP(network, address string, url *url.URL) *FastRP {
|
||||||
|
roundTripper := &http.Transport{
|
||||||
|
DialContext: func(_ context.Context, _ string, _ string) (net.Conn, error) {
|
||||||
|
return net.Dial(network, address)
|
||||||
|
},
|
||||||
|
MaxIdleConns: 10,
|
||||||
|
}
|
||||||
|
frp := &FastRP{
|
||||||
|
rp: httputil.NewSingleHostReverseProxy(url),
|
||||||
|
connPool: &sync.Pool{
|
||||||
|
New: func() any {
|
||||||
|
return roundTripper.Clone()
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
frp.rp.Transport = frp.connPool.Get().(http.RoundTripper)
|
||||||
|
return frp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (frp *FastRP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
roundTripper := frp.connPool.Get().(http.RoundTripper)
|
||||||
|
defer frp.connPool.Put(roundTripper)
|
||||||
|
frp.rp.Transport = roundTripper
|
||||||
|
frp.rp.ServeHTTP(w, r)
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user