Documentation
¶
Overview ¶
Package guard 实现入侵防护模块(类似 fail2ban):按日志规则、诱饵端口与端口扫描检测发现恶意 IP, 写入共享封禁表(internal/banlist),并同步到系统防火墙(nftables)在内核层丢弃其全部流量。
没有 nftables 或权限不足的平台(Windows、macOS、未授予 NET_ADMIN 的容器等)只在 Gately 自身的服务上生效, 诱饵端口退化为用户态监听,端口扫描检测不可用。
Index ¶
- Constants
- Variables
- func ManualBan(input string, seconds int, reason, requester string, s Settings) (banlist.Entry, error)
- type BanView
- type Deps
- type FirewallStatus
- type Jail
- type JailView
- type Module
- func (m *Module) ID() string
- func (m *Module) Init(env module.Env) error
- func (m *Module) Metrics() []module.Sample
- func (m *Module) Routes(r module.Router)
- func (m *Module) SelfCheck(_ context.Context, _ module.CheckEnv) []module.CheckResult
- func (m *Module) Start(ctx context.Context) error
- func (m *Module) Stop() error
- func (m *Module) Summary() []module.SummaryItem
- func (m *Module) Title() string
- type Platform
- type ScanSettings
- type Settings
- type Status
- type TestResult
- type TrapSettings
Constants ¶
const ( ReasonDisabled = "disabled" ReasonOS = "os" ReasonMissing = "missing" ReasonPermission = "permission" ReasonError = "error" // ReasonUnsupported 表示内核没有 nf_tables(如群晖 DSM),补装软件包也无法解决,不再重试 ReasonUnsupported = "unsupported" )
防火墙不可用的原因代码,由前端翻译
const ( BackendNFT = "nftables" BackendIPT = "iptables" )
防火墙后端
const ( // SourceFile 跟踪日志文件新增的内容,Target 为文件路径,每行一个 SourceFile = "file" // SourceJournal 跟踪 systemd 日志,Target 为服务单元名,每行一个 SourceJournal = "journal" // SourceCommand 运行一条持续输出日志的命令(例如 OpenWrt 的 logread -f),Target 为命令 SourceCommand = "command" // SourceDocker 跟踪 Docker 容器的日志,Target 为容器名 SourceDocker = "docker" // SourceEvent 统计 Gately 内部事件(管理后台登录失败、WAF 拦截、端口敲门被拒绝、文件服务登录失败),Target 为事件类型 SourceEvent = "event" // SourceWeb 统计 Web 服务的请求(路径探测),Target 为限定的监听 key,每行一个,留空表示全部监听; // Filter、Ignore 为路径规则,见 compilePaths SourceWeb = "web" // SourceTLS 统计 Web 服务的 TLS 握手失败,Target 为限定的监听 key,每行一个,留空表示全部监听; // Filter 为要统计的原因类别(webprobe.TLSKinds),每行一个,Ignore 不使用 SourceTLS = "tls" )
规则的日志来源
const ID = "guard"
ID 是模块标识。
Variables ¶
var Presets = []Jail{ { Preset: "sshd", Name: "SSH", Source: SourceFile, Target: "/var/log/auth.log", Filter: sshdFilter, MaxRetry: 5, FindTime: 600, }, { Preset: "sshd-journal", Name: "SSH (journald)", Source: SourceJournal, Target: "ssh.service\nsshd.service", Filter: sshdFilter, MaxRetry: 5, FindTime: 600, }, { Preset: "dropbear", Name: "Dropbear", Source: SourceCommand, Target: "logread -f", Filter: `Bad password attempt for '.*' from <HOST>:\d+\s*$ Login attempt for nonexistent user from <HOST>:\d+\s*$`, MaxRetry: 5, FindTime: 600, }, { Preset: "nginx-http-auth", Name: "Nginx Basic Auth", Source: SourceFile, Target: "/var/log/nginx/error.log", Filter: `user ".*":? (?:password mismatch|was not found in "[^"]*"), client: <HOST>, server: \S*, request: "\S+ \S+ HTTP/[\d.]+"(?:, host: "\S+")?(?:, referrer: "\S+")?\s*$`, MaxRetry: 5, FindTime: 600, }, { Preset: "nginx-botsearch", Name: "Nginx Bot Search", Source: SourceFile, Target: "/var/log/nginx/access.log", Filter: `^<HOST> \S+ \S+ \[[^\]]+\] "(?:GET|POST|HEAD) [^"]*(?:wp-login\.php|xmlrpc\.php|/wp-admin|phpmyadmin|/pma/|/\.env|/\.git/|/cgi-bin/|/boaform/|/HNAP1|/vendor/phpunit|/actuator/)[^"]*" (?:400|401|403|404|405) `, MaxRetry: 3, FindTime: 600, BanTime: 86400, }, { Preset: "vaultwarden", Name: "Vaultwarden", Source: SourceDocker, Target: "vaultwarden", Filter: `Username or password is incorrect\. Try again\. IP: <HOST>\. Username: Invalid TOTP code! Server time: .* IP: <HOST>\s*$`, MaxRetry: 5, FindTime: 600, }, { Preset: "homeassistant", Name: "Home Assistant", Source: SourceDocker, Target: "homeassistant", Filter: `Login attempt or request with invalid authentication from \S+ \(<HOST>\)`, MaxRetry: 5, FindTime: 600, }, { Preset: "proxmox", Name: "Proxmox VE", Source: SourceJournal, Target: "pvedaemon.service", Filter: `authentication (?:failure|error); rhost=(?:::ffff:)?<HOST> user=`, MaxRetry: 5, FindTime: 600, }, { Preset: "gately-admin", Name: "Gately 管理后台", Source: SourceEvent, Target: events.AuthFailed, MaxRetry: 5, FindTime: 600, }, { Preset: "gately-waf", Name: "WAF 拦截", Source: SourceEvent, Target: events.WAFBlocked, MaxRetry: 5, FindTime: 300, BanTime: 86400, }, { Preset: "gately-knock", Name: "端口敲门失败", Source: SourceEvent, Target: events.KnockFailed, MaxRetry: 5, FindTime: 600, BanTime: 86400, }, { Preset: "gately-files", Name: "文件服务登录失败", Source: SourceEvent, Target: events.FileAuthFailed, MaxRetry: 10, FindTime: 600, }, { Preset: "web-decoy", Name: "Web 诱饵路径", Source: SourceWeb, Filter: decoyPaths, AnyStatus: true, MaxRetry: 1, FindTime: 600, BanTime: 86400, }, { Preset: "web-unknown-host", Name: "未知域名扫描", Source: SourceWeb, UnknownHost: true, MaxRetry: 5, FindTime: 60, BanTime: 86400, }, { Preset: "web-404", Name: "Web 404 探测", Source: SourceWeb, Ignore: "/favicon.ico\n/apple-touch-icon*\n/robots.txt\n*.map", MaxRetry: 10, FindTime: 60, }, { Preset: "tls-probe", Name: "TLS 异常握手", Source: SourceTLS, Filter: "protocol\nnegotiation", MaxRetry: 5, FindTime: 60, BanTime: 86400, }, { Preset: "tls-abort", Name: "TLS 握手中断", Source: SourceTLS, Filter: "eof\nreset\ntimeout", MaxRetry: 20, FindTime: 60, }, }
Presets 是常见服务的规则模板,界面按 Preset 字段翻译名称与说明。 过滤规则参考 fail2ban 的同名过滤器,按 Go 正则(RE2)改写并精简。
Functions ¶
Types ¶
type Deps ¶
type Deps struct {
// FollowDocker 持续读取容器新产生的日志行,直到 ctx 取消或出错;Docker 模块关闭时为 nil
FollowDocker func(ctx context.Context, container string, onLine func(string)) error
}
Deps 是由装配处注入的外部能力,避免模块之间直接依赖。
type FirewallStatus ¶
type FirewallStatus struct {
// Enabled 为设置中是否开启同步
Enabled bool `json:"enabled"`
// Active 为规则是否已写入系统防火墙
Active bool `json:"active"`
// Reason 为不可用原因代码,Error 为具体错误
Reason string `json:"reason,omitempty"`
Error string `json:"error,omitempty"`
Version string `json:"version,omitempty"`
// Backend 为写入规则使用的防火墙:nftables,或内核没有 nf_tables 时的 iptables(legacy + ipset)
Backend string `json:"backend,omitempty"`
// Dropped 为各类规则丢弃的数据包数:ban(封禁表)、deny(网段与永久封禁);
// 旧版本由内核直接封禁诱饵端口与扫描来源时还有 trap、scan,升级后保留累计值
Dropped map[string]uint64 `json:"dropped"`
// Hits 为诱饵端口与扫描检测经 Gately 完成握手确认的连接数
Hits map[string]uint64 `json:"hits"`
// Redirect 为诱饵端口与扫描检测的重定向规则是否已写入:为 false 且规则已生效时,内核不支持重定向,
// 诱饵端口改由 Gately 直接监听,扫描检测不可用
Redirect bool `json:"redirect"`
// OpenPorts 为扫描检测视为开放的端口数
OpenPorts int `json:"openPorts"`
// TrapPorts 为实际生效的诱饵端口,TrapSkipped 为因正在监听而排除的诱饵端口
TrapPorts string `json:"trapPorts"`
TrapSkipped []int `json:"trapSkipped"`
CheckedAt time.Time `json:"checkedAt,omitzero"`
}
FirewallStatus 是防火墙同步状态。
type Jail ¶
type Jail struct {
Key string `json:"key"`
Name string `json:"name"`
// Group 为列表中的分组名称,只影响管理界面的展示,留空为未分组
Group string `json:"group"`
Enable bool `json:"enable"`
// Source 为日志来源,见 Source* 常量
Source string `json:"source"`
// Target 为来源参数:文件路径、服务单元、命令、容器名或事件类型
Target string `json:"target"`
// Filter 为失败记录的正则,每行一条,用 <HOST> 表示来源地址;内部事件来源可留空
Filter string `json:"filter"`
// Ignore 为排除的正则,每行一条,匹配的行不计数
Ignore string `json:"ignore"`
// MaxRetry 为触发封禁的失败次数
MaxRetry int `json:"maxRetry"`
// FindTime 为统计窗口(秒)
FindTime int `json:"findTime"`
// BanTime 为封禁时长(秒),0 表示沿用默认时长,-1 表示永久
BanTime int `json:"banTime"`
// AnyStatus 只用于 Web 路径探测:为 true 时任何状态码都计数,默认只统计 404 与 444
AnyStatus bool `json:"anyStatus,omitempty"`
// UnknownHost 只用于 Web 路径探测:为 true 时只统计域名未匹配任何站点的请求(默认站点或没有站点)
UnknownHost bool `json:"unknownHost,omitempty"`
// Preset 为创建时使用的预设 ID,只用于界面展示
Preset string `json:"preset,omitempty"`
Remark string `json:"remark"`
}
Jail 是一条检测规则:在日志中按正则找出失败记录,同一来源在 FindTime 内达到 MaxRetry 次即被封禁。
type JailView ¶
type JailView struct {
Jail
Running bool `json:"running"`
Matches int64 `json:"matches"`
Bans int64 `json:"bans"`
Active int `json:"active"`
Error string `json:"error,omitempty"`
LastSeen time.Time `json:"lastSeen,omitzero"`
}
JailView 是带运行状态的规则。
type Module ¶
type Module struct {
// contains filtered or unexported fields
}
Module 是入侵防护模块。
func (*Module) Summary ¶
func (m *Module) Summary() []module.SummaryItem
Summary 实现 module.Summarizer。
type Platform ¶
type Platform struct {
OS string `json:"os"`
InDocker bool `json:"inDocker"`
// Journal 为是否找到 journalctl,Docker 为 Docker 管理模块是否开启
Journal bool `json:"journal"`
Docker bool `json:"docker"`
}
Platform 是运行环境信息。
type ScanSettings ¶
type ScanSettings struct {
Enable bool `json:"enable"`
// Threshold 为每分钟允许的未开放端口连接次数
Threshold int `json:"threshold"`
// ExcludePorts 为额外视为开放的端口(例如由其他防火墙规则转发的端口),格式同诱饵端口
ExcludePorts string `json:"excludePorts"`
BanSeconds int `json:"banSeconds"`
// IPv6Strict 为 true 时 IPv6 来源只允许连接开放端口(正在监听的端口加 ExcludePorts),
// 第一次连接其他端口即被封禁,不再按 Threshold 计数;IPv4 仍按阈值检测。仅在扫描检测启用时生效
IPv6Strict bool `json:"ipv6Strict"`
}
ScanSettings 是端口扫描检测设置:同一来源每分钟连接本机未开放端口的次数超过阈值即被封禁。
type Settings ¶
type Settings struct {
// Firewall 为 true 时把封禁同步到 nftables,在内核层丢弃被封禁地址的全部流量
Firewall bool `json:"firewall"`
// BanSeconds 为默认封禁时长
BanSeconds int `json:"banSeconds"`
// Increment 为 true 时同一地址再次被封禁的时长翻倍,最长 MaxBanSeconds
Increment bool `json:"increment"`
MaxBanSeconds int `json:"maxBanSeconds"`
// IgnorePrivate 为 true 时内网、回环与链路本地地址不会被自动封禁
IgnorePrivate bool `json:"ignorePrivate"`
// IgnoreList 为白名单 IP 或网段
IgnoreList []string `json:"ignoreList"`
Trap TrapSettings `json:"trap"`
Scan ScanSettings `json:"scan"`
}
Settings 是模块全局设置。
type Status ¶
type Status struct {
Firewall FirewallStatus `json:"firewall"`
// Bans 为当前封禁数量
Bans int `json:"bans"`
// UserTrapPorts 为防火墙不可用时由 Gately 自己监听的诱饵端口
UserTrapPorts []int `json:"userTrapPorts"`
// Platform 描述运行环境,界面据此提示可用的日志来源
Platform Platform `json:"platform"`
}
Status 是模块运行状态。
type TestResult ¶
type TestResult struct {
Line string `json:"line"`
Matched bool `json:"matched"`
Host string `json:"host,omitempty"`
// Kind 为 TLS 握手失败规则测试时该原因所属的类别
Kind string `json:"kind,omitempty"`
// Ignored 为 true 表示地址在白名单中,不会计数
Ignored bool `json:"ignored,omitempty"`
}
TestResult 是一行日志的测试结果。
type TrapSettings ¶
type TrapSettings struct {
Enable bool `json:"enable"`
// Ports 为端口列表,逗号或换行分隔,支持 5900-5910 这样的范围
Ports string `json:"ports"`
// BanSeconds 为封禁时长,0 表示沿用默认时长
BanSeconds int `json:"banSeconds"`
}
TrapSettings 是诱饵端口设置:任何来源连接这些端口即被封禁。