traefik/pkg/middlewares/tcp/ipallowlist/ip_allowlist.go

66 lines
1.7 KiB
Go
Raw Normal View History

2022-10-26 15:42:07 +00:00
package ipallowlist
2021-06-11 13:30:05 +00:00
import (
"context"
"errors"
"fmt"
"github.com/traefik/traefik/v2/pkg/config/dynamic"
"github.com/traefik/traefik/v2/pkg/ip"
"github.com/traefik/traefik/v2/pkg/log"
"github.com/traefik/traefik/v2/pkg/middlewares"
"github.com/traefik/traefik/v2/pkg/tcp"
)
const (
2022-10-26 15:16:05 +00:00
typeName = "IPAllowListerTCP"
2021-06-11 13:30:05 +00:00
)
2022-10-26 15:16:05 +00:00
// ipAllowLister is a middleware that provides Checks of the Requesting IP against a set of Allowlists.
type ipAllowLister struct {
2021-06-11 13:30:05 +00:00
next tcp.Handler
2022-10-26 15:16:05 +00:00
allowLister *ip.Checker
2021-06-11 13:30:05 +00:00
name string
}
2022-10-26 15:16:05 +00:00
// New builds a new TCP IPAllowLister given a list of CIDR-Strings to allow.
func New(ctx context.Context, next tcp.Handler, config dynamic.TCPIPAllowList, name string) (tcp.Handler, error) {
2021-06-11 13:30:05 +00:00
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
logger.Debug("Creating middleware")
if len(config.SourceRange) == 0 {
2022-10-26 15:16:05 +00:00
return nil, errors.New("sourceRange is empty, IPAllowLister not created")
2021-06-11 13:30:05 +00:00
}
checker, err := ip.NewChecker(config.SourceRange)
if err != nil {
2022-10-26 15:16:05 +00:00
return nil, fmt.Errorf("cannot parse CIDRs %s: %w", config.SourceRange, err)
2021-06-11 13:30:05 +00:00
}
2022-10-26 15:16:05 +00:00
logger.Debugf("Setting up IPAllowLister with sourceRange: %s", config.SourceRange)
2021-06-11 13:30:05 +00:00
2022-10-26 15:16:05 +00:00
return &ipAllowLister{
allowLister: checker,
2021-06-11 13:30:05 +00:00
next: next,
name: name,
}, nil
}
2022-10-26 15:16:05 +00:00
func (al *ipAllowLister) ServeTCP(conn tcp.WriteCloser) {
ctx := middlewares.GetLoggerCtx(context.Background(), al.name, typeName)
2021-06-11 13:30:05 +00:00
logger := log.FromContext(ctx)
addr := conn.RemoteAddr().String()
2022-10-26 15:16:05 +00:00
err := al.allowLister.IsAuthorized(addr)
2021-06-11 13:30:05 +00:00
if err != nil {
logger.Errorf("Connection from %s rejected: %v", addr, err)
conn.Close()
return
}
logger.Debugf("Connection from %s accepted", addr)
2022-10-26 15:16:05 +00:00
al.next.ServeTCP(conn)
2021-06-11 13:30:05 +00:00
}