Compare commits
No commits in common. "main" and "v0.1.0" have entirely different histories.
@ -2,8 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/sha1"
|
"crypto/sha256"
|
||||||
"fmt"
|
|
||||||
"gitea.illuad.fr/adrien/middleman/command"
|
"gitea.illuad.fr/adrien/middleman/command"
|
||||||
"github.com/rs/zerolog/log"
|
"github.com/rs/zerolog/log"
|
||||||
"github.com/urfave/cli/v3"
|
"github.com/urfave/cli/v3"
|
||||||
@ -20,26 +19,37 @@ type noCommit struct {
|
|||||||
|
|
||||||
func (nc noCommit) String() string {
|
func (nc noCommit) String() string {
|
||||||
if nc.message == nil {
|
if nc.message == nil {
|
||||||
nc.message = []byte("not tied to a commit") // dbf242029aeedcfe71af2e5843474d8f8e2e9d63
|
nc.message = []byte("not tied to a commit") // 6344da387a21711b36a91c2fd55f48a026b2be8b5345cbbf32a31f5c089f4d75
|
||||||
}
|
}
|
||||||
sum := sha1.Sum(nc.message)
|
sum := sha256.Sum256(nc.message)
|
||||||
return fmt.Sprintf("%x", sum)
|
return string(sum[:])
|
||||||
}
|
}
|
||||||
|
|
||||||
const appName = "middleman"
|
const appName = "middleman"
|
||||||
|
|
||||||
var version, commit string
|
var (
|
||||||
|
version = "dev"
|
||||||
|
commit = noCommit{}.String()
|
||||||
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
info, ok := debug.ReadBuildInfo()
|
||||||
|
if ok {
|
||||||
|
if info.Main.Version != "" {
|
||||||
|
version = info.Main.Version
|
||||||
|
commit = info.Main.Sum
|
||||||
|
}
|
||||||
|
}
|
||||||
// Note: os.Kill/syscall.SIGKILL (SIGKILL) signal cannot be caught or ignored.
|
// Note: os.Kill/syscall.SIGKILL (SIGKILL) signal cannot be caught or ignored.
|
||||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
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: version + "-" + commit,
|
||||||
|
DefaultCommand: command.ServeCmd,
|
||||||
Commands: []*cli.Command{
|
Commands: []*cli.Command{
|
||||||
command.Serve(group),
|
command.Serve(group),
|
||||||
command.Healthcheck(group),
|
command.Healthcheck(group),
|
||||||
@ -56,18 +66,3 @@ func main() {
|
|||||||
log.Err(err).Send()
|
log.Err(err).Send()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildVersion() string {
|
|
||||||
info, ok := debug.ReadBuildInfo()
|
|
||||||
if ok {
|
|
||||||
if info.Main.Version != "" {
|
|
||||||
version = info.Main.Version
|
|
||||||
commit = info.Main.Sum
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if version == "" && commit == "" {
|
|
||||||
version = "dev"
|
|
||||||
commit = noCommit{}.String()
|
|
||||||
}
|
|
||||||
return version + "-" + commit
|
|
||||||
}
|
|
||||||
|
136
command/serve.go
136
command/serve.go
@ -6,16 +6,15 @@ 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"
|
||||||
)
|
)
|
||||||
@ -35,7 +34,25 @@ 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 {
|
||||||
frp *fastrp.FastRP
|
rp *httputil.ReverseProxy
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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.
|
||||||
@ -75,8 +92,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"
|
||||||
// defaultAllowedRequests is the default allowed requests. Note that they should be sufficient to make Traefik work properly.
|
// defaultAllowedRequest is the proxy default allowed request.
|
||||||
defaultAllowedRequests = "/v1.\\d{1,2}/(version|containers/(?:json|[a-zA-Z0-9]{64}/json)|events)$"
|
defaultAllowedRequest = "^/(version|containers/.*|events.*)$"
|
||||||
)
|
)
|
||||||
|
|
||||||
var s serve
|
var s serve
|
||||||
@ -84,7 +101,7 @@ var s serve
|
|||||||
var (
|
var (
|
||||||
containerMethodRegex = map[string]methodRegex{
|
containerMethodRegex = map[string]methodRegex{
|
||||||
"*": {
|
"*": {
|
||||||
http.MethodGet: regexp.MustCompile(defaultAllowedRequests),
|
http.MethodGet: regexp.MustCompile(defaultAllowedRequest),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
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))*)?)\):(.*)$`)
|
||||||
@ -131,75 +148,54 @@ 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("method", r.Method).Str("path", r.URL.Path).Msg("incoming request")
|
log.Debug().Str("http_method", r.Method).Str("path", r.URL.Path).Msg("incoming request")
|
||||||
if mr, ok := containerMethodRegex["*"]; ok {
|
mr, ok := containerMethodRegex["*"]
|
||||||
if code := ph.checkMethodAndRegex(mr, r, ""); code != http.StatusOK {
|
if ok {
|
||||||
http.Error(w, http.StatusText(code), code)
|
if err := checkMethodPath(w, r, mr); err != nil {
|
||||||
|
log.Err(err).Send()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ph.frp.ServeHTTP(w, r)
|
} else {
|
||||||
return
|
var (
|
||||||
}
|
containerName string
|
||||||
host, _, _ := net.SplitHostPort(r.RemoteAddr)
|
host, _, _ = net.SplitHostPort(r.RemoteAddr)
|
||||||
for containerName, mr := range containerMethodRegex {
|
ip = net.ParseIP(host)
|
||||||
if ph.isContainerAuthorized(containerName, host) {
|
)
|
||||||
if code := ph.checkMethodAndRegex(mr, r, containerName); code != http.StatusOK {
|
for containerName, mr = range containerMethodRegex {
|
||||||
http.Error(w, http.StatusText(code), code)
|
resolvedIPs, err := net.LookupIP(containerName)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ph.frp.ServeHTTP(w, r)
|
for _, resolvedIP := range resolvedIPs {
|
||||||
return
|
if resolvedIP.Equal(ip) {
|
||||||
|
if err = checkMethodPath(w, r, mr); err != nil {
|
||||||
|
log.Err(err).Send()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
logDeniedRequest(r, http.StatusUnauthorized, "this container is not on the list of authorized ones")
|
ph.rp.ServeHTTP(w, r)
|
||||||
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ph *ProxyHandler) isContainerAuthorized(containerName, host string) bool {
|
// checkMethodPath executes the regular expression on the path of the HTTP request if and only if
|
||||||
resolvedIPs, err := net.LookupIP(containerName)
|
// the latter's HTTP method is actually present in the list of authorized HTTP methods.
|
||||||
if err != nil {
|
func checkMethodPath(w http.ResponseWriter, r *http.Request, mr methodRegex) error {
|
||||||
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 {
|
||||||
logDeniedRequest(r, http.StatusMethodNotAllowed, "this HTTP method is not in the list of those authorized for this container")
|
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
||||||
return http.StatusMethodNotAllowed
|
return ErrHTTPMethodNotAllowed{httpMethod: r.Method}
|
||||||
}
|
}
|
||||||
if !req.MatchString(r.URL.Path) {
|
if !req.MatchString(r.URL.Path) {
|
||||||
logDeniedRequest(r, http.StatusForbidden, "this path does not match any regular expression for this HTTP method")
|
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
|
||||||
return http.StatusForbidden
|
return ErrNoMatch{
|
||||||
|
path: r.URL.Path,
|
||||||
|
httpMethod: r.Method,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
logAuthorizedRequest(r, containerName, "incoming request matches a registered regular expression")
|
return nil
|
||||||
return http.StatusOK
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// action is executed when the ServeCmd command is called.
|
// action is executed when the ServeCmd command is called.
|
||||||
@ -217,11 +213,15 @@ func (s serve) action(ctx context.Context, command *cli.Command) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
dummyURL, _ := url.Parse("http://dummy")
|
dummyURL, _ := url.Parse("http://dummy")
|
||||||
srv := &http.Server{ // #nosec: G112
|
rp := httputil.NewSingleHostReverseProxy(dummyURL)
|
||||||
Handler: &ProxyHandler{
|
rp.Transport = &http.Transport{
|
||||||
frp: fastrp.NewRP("unix", command.String(dockerSocketPathFlagName), dummyURL),
|
DialContext: func(_ context.Context, _ string, _ string) (net.Conn, error) {
|
||||||
|
return net.Dial("unix", command.String(dockerSocketPathFlagName))
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
srv := &http.Server{ // #nosec: G112
|
||||||
|
Handler: &ProxyHandler{rp: rp},
|
||||||
|
}
|
||||||
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) {
|
||||||
return err
|
return err
|
||||||
@ -418,9 +418,9 @@ func addRequests() cli.Flag {
|
|||||||
Category: "network",
|
Category: "network",
|
||||||
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{"*:" + defaultAllowedRequests},
|
Value: []string{"*:" + defaultAllowedRequest},
|
||||||
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)
|
||||||
for _, request := range requests {
|
for _, request := range requests {
|
||||||
|
@ -1,41 +0,0 @@
|
|||||||
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