mirror of
https://github.com/netbirdio/netbird.git
synced 2026-05-31 13:09:55 +00:00
Adds a new "private" service mode for the reverse proxy: services reachable exclusively over the embedded WireGuard tunnel, gated by per-peer group membership instead of operator auth schemes. Wire contract - ProxyMapping.private (field 13): the proxy MUST call ValidateTunnelPeer and fail closed; operator schemes are bypassed. - ProxyCapabilities.private (4) + supports_private_service (5): capability gate. Management never streams private mappings to proxies that don't claim the capability; the broadcast path applies the same filter via filterMappingsForProxy. - ValidateTunnelPeer RPC: resolves an inbound tunnel IP to a peer, checks the peer's groups against service.AccessGroups, and mints a session JWT on success. checkPeerGroupAccess fails closed when a private service has empty AccessGroups. - ValidateSession/ValidateTunnelPeer responses now carry peer_group_ids + peer_group_names so the proxy can authorise policy-aware middlewares without an extra management round-trip. - ProxyInboundListener + SendStatusUpdate.inbound_listener: per-account inbound listener state surfaced to dashboards. - PathTargetOptions.direct_upstream (11): bypass the embedded NetBird client and dial the target via the proxy host's network stack for upstreams reachable without WireGuard. Data model - Service.Private (bool) + Service.AccessGroups ([]string, JSON- serialised). Validate() rejects bearer auth on private services. Copy() deep-copies AccessGroups. pgx getServices loads the columns. - DomainConfig.Private threaded into the proxy auth middleware. Request handler routes private services through forwardWithTunnelPeer and returns 403 on validation failure. - Account-level SynthesizePrivateServiceZones (synthetic DNS) and injectPrivateServicePolicies (synthetic ACL) gate on len(svc.AccessGroups) > 0. Proxy - /netbird proxy --private (embedded mode) flag; Config.Private in proxy/lifecycle.go. - Per-account inbound listener (proxy/inbound.go) binding HTTP/HTTPS on the embedded NetBird client's WireGuard tunnel netstack. - proxy/internal/auth/tunnel_cache: ValidateTunnelPeer response cache with single-flight de-duplication and per-account eviction. - Local peerstore short-circuit: when the inbound IP isn't in the account roster, deny fast without an RPC. - proxy/server.go reports SupportsPrivateService=true and redacts the full ProxyMapping JSON from info logs (auth_token + header-auth hashed values now only at debug level). Identity forwarding - ValidateSessionJWT returns user_id, email, method, groups, group_names. sessionkey.Claims carries Email + Groups + GroupNames so the proxy can stamp identity onto upstream requests without an extra management round-trip on every cookie-bearing request. - CapturedData carries userEmail / userGroups / userGroupNames; the proxy stamps X-NetBird-User and X-NetBird-Groups on r.Out from the authenticated identity (strips client-supplied values first to prevent spoofing). - AccessLog.UserGroups: access-log enrichment captures the user's group memberships at write time so the dashboard can render group context without reverse-resolving stale memberships. OpenAPI/dashboard surface - ReverseProxyService gains private + access_groups; ReverseProxyCluster gains private + supports_private. ReverseProxyTarget target_type enum gains "cluster". ServiceTargetOptions gains direct_upstream. ProxyAccessLog gains user_groups.
328 lines
8.3 KiB
Go
328 lines
8.3 KiB
Go
// Package restrict provides connection-level access control based on
|
|
// IP CIDR ranges and geolocation (country codes).
|
|
package restrict
|
|
|
|
import (
|
|
"net/netip"
|
|
"slices"
|
|
"strings"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"github.com/netbirdio/netbird/proxy/internal/geolocation"
|
|
)
|
|
|
|
// defaultLogger is used when no logger is provided to ParseFilter.
|
|
var defaultLogger = log.NewEntry(log.StandardLogger())
|
|
|
|
// GeoResolver resolves an IP address to geographic information.
|
|
type GeoResolver interface {
|
|
LookupAddr(addr netip.Addr) geolocation.Result
|
|
Available() bool
|
|
}
|
|
|
|
// DecisionType is the type of CrowdSec remediation action.
|
|
type DecisionType string
|
|
|
|
const (
|
|
DecisionBan DecisionType = "ban"
|
|
DecisionCaptcha DecisionType = "captcha"
|
|
DecisionThrottle DecisionType = "throttle"
|
|
)
|
|
|
|
// CrowdSecDecision holds the type of a CrowdSec decision.
|
|
type CrowdSecDecision struct {
|
|
Type DecisionType
|
|
}
|
|
|
|
// CrowdSecChecker queries CrowdSec decisions for an IP address.
|
|
type CrowdSecChecker interface {
|
|
CheckIP(addr netip.Addr) *CrowdSecDecision
|
|
Ready() bool
|
|
}
|
|
|
|
// CrowdSecMode is the per-service enforcement mode.
|
|
type CrowdSecMode string
|
|
|
|
const (
|
|
CrowdSecOff CrowdSecMode = ""
|
|
CrowdSecEnforce CrowdSecMode = "enforce"
|
|
CrowdSecObserve CrowdSecMode = "observe"
|
|
)
|
|
|
|
// Filter evaluates IP restrictions. CIDR checks are performed first
|
|
// (cheap), followed by country lookups (more expensive) only when needed.
|
|
type Filter struct {
|
|
AllowedCIDRs []netip.Prefix
|
|
BlockedCIDRs []netip.Prefix
|
|
AllowedCountries []string
|
|
BlockedCountries []string
|
|
CrowdSec CrowdSecChecker
|
|
CrowdSecMode CrowdSecMode
|
|
}
|
|
|
|
// FilterConfig holds the raw configuration for building a Filter.
|
|
type FilterConfig struct {
|
|
AllowedCIDRs []string
|
|
BlockedCIDRs []string
|
|
AllowedCountries []string
|
|
BlockedCountries []string
|
|
CrowdSec CrowdSecChecker
|
|
CrowdSecMode CrowdSecMode
|
|
Logger *log.Entry
|
|
}
|
|
|
|
// ParseFilter builds a Filter from the config. Returns nil if no restrictions
|
|
// are configured.
|
|
func ParseFilter(cfg FilterConfig) *Filter {
|
|
hasCS := cfg.CrowdSecMode == CrowdSecEnforce || cfg.CrowdSecMode == CrowdSecObserve
|
|
if len(cfg.AllowedCIDRs) == 0 && len(cfg.BlockedCIDRs) == 0 &&
|
|
len(cfg.AllowedCountries) == 0 && len(cfg.BlockedCountries) == 0 && !hasCS {
|
|
return nil
|
|
}
|
|
|
|
logger := cfg.Logger
|
|
if logger == nil {
|
|
logger = defaultLogger
|
|
}
|
|
|
|
f := &Filter{
|
|
AllowedCountries: normalizeCountryCodes(cfg.AllowedCountries),
|
|
BlockedCountries: normalizeCountryCodes(cfg.BlockedCountries),
|
|
}
|
|
if hasCS {
|
|
f.CrowdSec = cfg.CrowdSec
|
|
f.CrowdSecMode = cfg.CrowdSecMode
|
|
}
|
|
for _, cidr := range cfg.AllowedCIDRs {
|
|
prefix, err := netip.ParsePrefix(cidr)
|
|
if err != nil {
|
|
logger.Warnf("skip invalid allowed CIDR %q: %v", cidr, err)
|
|
continue
|
|
}
|
|
f.AllowedCIDRs = append(f.AllowedCIDRs, prefix.Masked())
|
|
}
|
|
for _, cidr := range cfg.BlockedCIDRs {
|
|
prefix, err := netip.ParsePrefix(cidr)
|
|
if err != nil {
|
|
logger.Warnf("skip invalid blocked CIDR %q: %v", cidr, err)
|
|
continue
|
|
}
|
|
f.BlockedCIDRs = append(f.BlockedCIDRs, prefix.Masked())
|
|
}
|
|
return f
|
|
}
|
|
|
|
func normalizeCountryCodes(codes []string) []string {
|
|
if len(codes) == 0 {
|
|
return nil
|
|
}
|
|
out := make([]string, len(codes))
|
|
for i, c := range codes {
|
|
out[i] = strings.ToUpper(c)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Verdict is the result of an access check.
|
|
type Verdict int
|
|
|
|
const (
|
|
// Allow indicates the address passed all checks.
|
|
Allow Verdict = iota
|
|
// DenyCIDR indicates the address was blocked by a CIDR rule.
|
|
DenyCIDR
|
|
// DenyCountry indicates the address was blocked by a country rule.
|
|
DenyCountry
|
|
// DenyGeoUnavailable indicates that country restrictions are configured
|
|
// but the geo lookup is unavailable.
|
|
DenyGeoUnavailable
|
|
// DenyCrowdSecBan indicates a CrowdSec "ban" decision.
|
|
DenyCrowdSecBan
|
|
// DenyCrowdSecCaptcha indicates a CrowdSec "captcha" decision.
|
|
DenyCrowdSecCaptcha
|
|
// DenyCrowdSecThrottle indicates a CrowdSec "throttle" decision.
|
|
DenyCrowdSecThrottle
|
|
// DenyCrowdSecUnavailable indicates enforce mode but the bouncer has not
|
|
// completed its initial sync.
|
|
DenyCrowdSecUnavailable
|
|
)
|
|
|
|
// String returns the deny reason string matching the HTTP auth mechanism names.
|
|
func (v Verdict) String() string {
|
|
switch v {
|
|
case Allow:
|
|
return "allow"
|
|
case DenyCIDR:
|
|
return "ip_restricted"
|
|
case DenyCountry:
|
|
return "country_restricted"
|
|
case DenyGeoUnavailable:
|
|
return "geo_unavailable"
|
|
case DenyCrowdSecBan:
|
|
return "crowdsec_ban"
|
|
case DenyCrowdSecCaptcha:
|
|
return "crowdsec_captcha"
|
|
case DenyCrowdSecThrottle:
|
|
return "crowdsec_throttle"
|
|
case DenyCrowdSecUnavailable:
|
|
return "crowdsec_unavailable"
|
|
default:
|
|
return "unknown"
|
|
}
|
|
}
|
|
|
|
// IsCrowdSec returns true when the verdict originates from a CrowdSec check.
|
|
func (v Verdict) IsCrowdSec() bool {
|
|
switch v {
|
|
case DenyCrowdSecBan, DenyCrowdSecCaptcha, DenyCrowdSecThrottle, DenyCrowdSecUnavailable:
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
// IsObserveOnly returns true when v is a CrowdSec verdict and the filter is in
|
|
// observe mode. Callers should log the verdict but not block the request.
|
|
func (f *Filter) IsObserveOnly(v Verdict) bool {
|
|
if f == nil {
|
|
return false
|
|
}
|
|
return v.IsCrowdSec() && f.CrowdSecMode == CrowdSecObserve
|
|
}
|
|
|
|
// CheckCIDR runs only the CIDR allow/block evaluation. Use this when
|
|
// country and CrowdSec checks don't apply — e.g. requests arriving
|
|
// from the WireGuard overlay, whose source addresses live in the
|
|
// CGNAT range and have no meaningful geolocation or IP-reputation
|
|
// data.
|
|
func (f *Filter) CheckCIDR(addr netip.Addr) Verdict {
|
|
if f == nil {
|
|
return Allow
|
|
}
|
|
return f.checkCIDR(addr.Unmap())
|
|
}
|
|
|
|
// Check evaluates whether addr is permitted. CIDR rules are evaluated
|
|
// first because they are O(n) prefix comparisons. Country rules run
|
|
// only when CIDR checks pass and require a geo lookup. CrowdSec checks
|
|
// run last.
|
|
func (f *Filter) Check(addr netip.Addr, geo GeoResolver) Verdict {
|
|
if f == nil {
|
|
return Allow
|
|
}
|
|
|
|
// Normalize v4-mapped-v6 (e.g. ::ffff:10.1.2.3) to plain v4 so that
|
|
// IPv4 CIDR rules match regardless of how the address was received.
|
|
addr = addr.Unmap()
|
|
|
|
if v := f.checkCIDR(addr); v != Allow {
|
|
return v
|
|
}
|
|
if v := f.checkCountry(addr, geo); v != Allow {
|
|
return v
|
|
}
|
|
return f.checkCrowdSec(addr)
|
|
}
|
|
|
|
func (f *Filter) checkCIDR(addr netip.Addr) Verdict {
|
|
if len(f.AllowedCIDRs) > 0 {
|
|
allowed := false
|
|
for _, prefix := range f.AllowedCIDRs {
|
|
if prefix.Contains(addr) {
|
|
allowed = true
|
|
break
|
|
}
|
|
}
|
|
if !allowed {
|
|
return DenyCIDR
|
|
}
|
|
}
|
|
|
|
for _, prefix := range f.BlockedCIDRs {
|
|
if prefix.Contains(addr) {
|
|
return DenyCIDR
|
|
}
|
|
}
|
|
return Allow
|
|
}
|
|
|
|
func (f *Filter) checkCountry(addr netip.Addr, geo GeoResolver) Verdict {
|
|
if len(f.AllowedCountries) == 0 && len(f.BlockedCountries) == 0 {
|
|
return Allow
|
|
}
|
|
|
|
if geo == nil || !geo.Available() {
|
|
return DenyGeoUnavailable
|
|
}
|
|
|
|
result := geo.LookupAddr(addr)
|
|
if result.CountryCode == "" {
|
|
// Unknown country: deny if an allowlist is active, allow otherwise.
|
|
// Blocklists are best-effort: unknown countries pass through since
|
|
// the default policy is allow.
|
|
if len(f.AllowedCountries) > 0 {
|
|
return DenyCountry
|
|
}
|
|
return Allow
|
|
}
|
|
|
|
if len(f.AllowedCountries) > 0 {
|
|
if !slices.Contains(f.AllowedCountries, result.CountryCode) {
|
|
return DenyCountry
|
|
}
|
|
}
|
|
|
|
if slices.Contains(f.BlockedCountries, result.CountryCode) {
|
|
return DenyCountry
|
|
}
|
|
|
|
return Allow
|
|
}
|
|
|
|
func (f *Filter) checkCrowdSec(addr netip.Addr) Verdict {
|
|
if f.CrowdSecMode == CrowdSecOff {
|
|
return Allow
|
|
}
|
|
|
|
// Checker nil with enforce means CrowdSec was requested but the proxy
|
|
// has no LAPI configured. Fail-closed.
|
|
if f.CrowdSec == nil {
|
|
if f.CrowdSecMode == CrowdSecEnforce {
|
|
return DenyCrowdSecUnavailable
|
|
}
|
|
return Allow
|
|
}
|
|
|
|
if !f.CrowdSec.Ready() {
|
|
if f.CrowdSecMode == CrowdSecEnforce {
|
|
return DenyCrowdSecUnavailable
|
|
}
|
|
return Allow
|
|
}
|
|
|
|
d := f.CrowdSec.CheckIP(addr)
|
|
if d == nil {
|
|
return Allow
|
|
}
|
|
|
|
switch d.Type {
|
|
case DecisionCaptcha:
|
|
return DenyCrowdSecCaptcha
|
|
case DecisionThrottle:
|
|
return DenyCrowdSecThrottle
|
|
default:
|
|
return DenyCrowdSecBan
|
|
}
|
|
}
|
|
|
|
// HasRestrictions returns true if any restriction rules are configured.
|
|
func (f *Filter) HasRestrictions() bool {
|
|
if f == nil {
|
|
return false
|
|
}
|
|
return len(f.AllowedCIDRs) > 0 || len(f.BlockedCIDRs) > 0 ||
|
|
len(f.AllowedCountries) > 0 || len(f.BlockedCountries) > 0 ||
|
|
f.CrowdSecMode == CrowdSecEnforce || f.CrowdSecMode == CrowdSecObserve
|
|
}
|