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

64 lines
1.6 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"
2023-02-03 14:24:05 +00:00
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/ip"
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/tcp"
2021-06-11 13:30:05 +00:00
)
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) {
2022-11-21 17:36:05 +00:00
logger := middlewares.GetLogger(ctx, name, typeName)
logger.Debug().Msg("Creating middleware")
2021-06-11 13:30:05 +00:00
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-11-21 17:36:05 +00:00
logger.Debug().Msgf("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) {
2022-11-21 17:36:05 +00:00
logger := middlewares.GetLogger(context.Background(), al.name, typeName)
2021-06-11 13:30:05 +00:00
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 {
2022-11-21 17:36:05 +00:00
logger.Error().Err(err).Msgf("Connection from %s rejected", addr)
2021-06-11 13:30:05 +00:00
conn.Close()
return
}
2022-11-21 17:36:05 +00:00
logger.Debug().Msgf("Connection from %s accepted", addr)
2021-06-11 13:30:05 +00:00
2022-10-26 15:16:05 +00:00
al.next.ServeTCP(conn)
2021-06-11 13:30:05 +00:00
}