sdk

package
v1.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 30 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sdk Engine 实现。

Engine 持有一个 *runner.Runner 实例,封装所有扫描业务状态:

  • FingerStore:当前 Engine 加载的指纹规则集
  • RulePool: 规则评估协程池
  • CacheManager:请求 / 响应缓存
  • PerformanceMonitor:内存与调度监控器
  • HostRateLimiter:可选的 per-host 令牌桶限流器

多个 Engine 可在同一进程并发存在,每个实例持有独立资源。

Package sdk 错误定义。

所有 SDK 返回的错误都通过 fmt.Errorf("%w", sentinel) 包装某个 sentinel error, 调用方使用 errors.Is / errors.As 判断错误类型:

if errors.Is(err, sdk.ErrEngineClosed) {
    // 处理引擎已关闭场景
}

Package sdk Functional Options 定义。

Engine 的所有配置通过 Option 注入,NewEngine 在构造期一次性 apply。

Package sdk 是 GXX 指纹识别引擎的对外入口。

所有扫描 API 都是 *Engine 的方法。Engine 通过 sdk.NewEngine 构造, 所有配置由 Functional Options(With* 系列)注入;不再使用时调用 Close 释放资源。

最小用法:

engine, err := sdk.NewEngine(ctx,
    sdk.WithFingerOptions(sdk.FingerOptions{PocFile: "fingerYaml"}),
    sdk.WithTimeout(15 * time.Second),
    sdk.WithRuleConcurrency(500),
)
if err != nil {
    return err
}
defer engine.Close()

result, err := engine.Scan(ctx, "https://example.com")
for _, m := range result.Matches { ... }

流式批量:

engine.ScanCallback(ctx, []string{...}, func(r *sdk.TargetResult) bool {
    ...
    return true
})

Package sdk 输出写入器(OutputWriter)。

Writer 是 SDK 自有的输出抽象,对每个完成扫描的 *TargetResult 执行落盘 / 转发动作。 所有内置实现都是实例化的:每个 Engine 通过 Option 注入自己的 Writer, 不依赖任何包级全局状态,多 Engine 可在同进程并发使用而互不污染。

可通过以下 Option 启用:

sdk.WithOutputFile("results.json", "json")
sdk.WithWriter(sockWriter)     // sockWriter 由 sdk.NewSockWriter("/tmp/gxx.sock") 创建
sdk.WithWriter(myCustomWriter) // 自行实现 Writer 接口

多个 Option 会被 MultiWriter 自动合并,写入失败只记录日志,不影响扫描主流程。

Index

Constants

View Source
const (
	MissingProduct          = "product"           // 规则没有产品声明,WithProductCatalog 也没有覆盖
	MissingVendor           = "vendor"            // 产品没有厂商
	MissingProductAssurance = "product-assurance" // 产品信息为推断(assurance 不是 verified)
	MissingTags             = "tags"              // 规则与产品都没有标签
	MissingReferences       = "references"        // 规则与产品都没有有效参考链接
	MissingServices         = "services"          // TCP/UDP 规则没有声明识别的服务
	MissingSampleValidation = "sample-validation" // 没有绑定当前规则内容的专项样本记录
	MissingVersionExtractor = "version-extractor" // 没有子规则输出 product_version
)

MissingMetadata 的取值,按以下顺序列出,表示尚需补充或核实的数据项,不代表规则失效。

View Source
const (
	RequestHTTP     = network.RequestHTTP
	RequestRaw      = network.RequestRaw
	RequestTCP      = network.RequestTCP
	RequestUDP      = network.RequestUDP
	RequestIcon     = network.RequestIcon
	RequestResource = network.RequestResource
	RequestTLS      = network.RequestTLS
)

出站连接的用途。

View Source
const (
	RedirectFollow = network.RedirectFollow
	RedirectStop   = network.RedirectStop
)

跳转决定。

View Source
const (
	StageRequest      = runner.StageRequest
	StageExpression   = runner.StageExpression
	StageNonBool      = runner.StageNonBool
	StageExtract      = runner.StageExtract
	StageRegexTimeout = runner.StageRegexTimeout
	StagePanic        = runner.StagePanic
	StageBudget       = runner.StageBudget
)

求值失败的原因。

View Source
const Version = "1.8.0"

Version 是 SDK 源版本,不能作为被识别产品的版本。

Variables

View Source
var (
	// ErrEmptyTarget 目标 URL 为空。
	ErrEmptyTarget = errors.New("sdk: target URL is empty")

	// ErrEngineClosed 引擎已经被 Close(),不能再执行扫描。
	ErrEngineClosed = errors.New("sdk: engine has been closed")

	// ErrEngineNotReady 引擎尚未完成初始化(指纹未加载、规则池未初始化等)。
	ErrEngineNotReady = errors.New("sdk: engine is not ready")

	// ErrFingerNotLoaded 指纹规则尚未加载或加载失败。
	ErrFingerNotLoaded = errors.New("sdk: finger rules not loaded")

	// ErrScanFailed 扫描过程中发生不可恢复错误。
	ErrScanFailed = errors.New("sdk: scan failed")

	// ErrInvalidOption Functional Option 入参非法(如 timeout < 0、cache size <= 0 等)。
	ErrInvalidOption = errors.New("sdk: invalid option")

	// ErrEmptyResult 扫描完成但底层返回空指针,通常意味着目标不可达或被防火墙拦截。
	ErrEmptyResult = errors.New("sdk: empty scan result")

	// ErrLoadFinger 指纹规则加载失败(YAML 文件不存在 / 格式错误等)。
	ErrLoadFinger = errors.New("sdk: load finger rules failed")

	// ErrRulePolicy 规则违反 WithRulePolicy 设置的规则策略;具体内容用 errors.As 取 *RulePolicyError。
	ErrRulePolicy = errors.New("sdk: rule violates policy")
)

Sentinel errors 集中定义,便于调用方做 errors.Is/As 判断。

Functions

This section is empty.

Types

type BaseInfo

type BaseInfo struct {
	Target     string      `json:"target"`
	FinalURL   string      `json:"final_url,omitempty"`
	RedirectTo string      `json:"redirect_to,omitempty"`
	Redirects  []Redirect  `json:"redirects,omitempty"`
	Title      string      `json:"title"`
	StatusCode int32       `json:"status_code"`
	Server     *ServerInfo `json:"server,omitempty"`
	TechStack  *TechStack  `json:"tech_stack,omitempty"`
	ICP        string      `json:"icp,omitempty"`
	Certs      []CertInfo  `json:"certs,omitempty"`
	// HeaderOrder、TLS、Icon 与 Resources 的含义与 TargetResult 相同。
	HeaderOrder []string      `json:"header_order,omitempty"`
	TLS         *TLSInfo      `json:"tls,omitempty"`
	Icon        *IconEvidence `json:"icon,omitempty"`
	Resources   []Resource    `json:"resources,omitempty"`
}

BaseInfo 目标基础信息(不含指纹匹配)。跳转字段的含义与 TargetResult 相同。

type CertInfo

type CertInfo struct {
	Subject               CertName `json:"subject"`
	Issuer                CertName `json:"issuer"`
	NotBefore             string   `json:"not_before"`
	NotAfter              string   `json:"not_after"`
	Valid                 bool     `json:"valid"`
	SerialNumber          string   `json:"serial_number"`
	PublicKeyAlgorithm    string   `json:"public_key_algorithm"`
	PublicKey             string   `json:"public_key,omitempty"`
	SignatureAlgorithm    string   `json:"signature_algorithm"`
	Version               int      `json:"version"`
	DNSNames              []string `json:"dns_names,omitempty"`
	IPAddresses           []string `json:"ip_addresses,omitempty"`
	EmailAddresses        []string `json:"email_addresses,omitempty"`
	URIs                  []string `json:"uris,omitempty"`
	OCSPServer            []string `json:"ocsp_server,omitempty"`
	CRLDistributionPoints []string `json:"crl_distribution_points,omitempty"`
	IssuingCertificateURL []string `json:"issuing_certificate_url,omitempty"`
}

CertInfo 证书信息。

type CertName

type CertName struct {
	CommonName         string   `json:"common_name,omitempty"`
	Organization       []string `json:"organization,omitempty"`
	OrganizationalUnit []string `json:"organizational_unit,omitempty"`
	Country            []string `json:"country,omitempty"`
	Province           []string `json:"province,omitempty"`
	Locality           []string `json:"locality,omitempty"`
	StreetAddress      []string `json:"street_address,omitempty"`
	PostalCode         []string `json:"postal_code,omitempty"`
	SerialNumber       string   `json:"serial_number_dn,omitempty"`
}

CertName 证书名称。

type DeniedError added in v1.8.0

type DeniedError = network.DeniedError

DeniedError 是被 NetworkPolicy.CheckTarget 拒绝的连接,Request 是被拒绝的目标。

type DetectionRule added in v1.2.0

type DetectionRule struct {
	Key        string            `json:"key"`
	Transport  string            `json:"transport"`
	Method     string            `json:"method"`
	Path       string            `json:"path"`
	Expression string            `json:"expression"`
	Output     map[string]string `json:"output,omitempty"`
}

DetectionRule 展示识别依据与版本提取表达式,不包含执行时的响应数据。

type Diagnostic added in v1.8.0

type Diagnostic struct {
	Code     string `json:"code"`
	Field    string `json:"field,omitempty"`
	Message  string `json:"message"`
	Severity string `json:"severity"`
	Line     int    `json:"line,omitempty"`
	Column   int    `json:"column,omitempty"`
}

Diagnostic 是规则校验发现的一处问题。Severity 为 "error" 或 "warning";Line、Column 从 1 开始,无法定位时为 0;Field 是字段路径,列表项用序号表示(如 info.services.0.ports)。 Code 取值:yaml(无法解析,含不支持的请求类型)、unknown-key、missing-id、missing-name、 missing-rules、missing-expression、expression-compile、invalid-product(产品声明缺少 必填项或取值不合规)、missing-services(TCP/UDP 规则没有声明服务)、invalid-service, 以及规则策略的 policy-type、policy-raw、policy-reverse、policy-sleep、policy-sub-rules。

func ValidateRule added in v1.8.0

func ValidateRule(content []byte, opts ValidateOptions) []Diagnostic

ValidateRule 校验一条规则的内容,不发请求,没有问题时返回空切片。

非严格模式下,存在 error 当且仅当使用同样 Policy 的 NewEngine 拒绝加载这条规则: YAML 无法解析(含不支持的请求类型)或违反规则策略;其他问题报告为 warning, 不影响加载。严格模式另把规范性问题报告为 error,用于规则入库前的检查。 库级限制 MaxRules 不适用于单条规则。

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine 指纹识别引擎实例。

func NewEngine

func NewEngine(ctx context.Context, opts ...Option) (*Engine, error)

NewEngine 创建并初始化 Engine 实例。

调用方负责在不再使用时执行 engine.Close() 释放资源。

engine, err := sdk.NewEngine(ctx,
    sdk.WithFingerOptions(sdk.FingerOptions{PocFile: "fingerYaml"}),
    sdk.WithTimeout(15 * time.Second),
    sdk.WithRuleConcurrency(500),
    sdk.WithRateLimit(50, 100),
)
if err != nil { return err }
defer engine.Close()

func (*Engine) Close

func (e *Engine) Close() error

Close 释放 Engine 持有的所有资源(线程安全,可重复调用)。

关闭顺序:取消并等待在途扫描,释放 Runner,再刷新并关闭 Writer。

func (*Engine) DebugRule added in v1.8.0

func (e *Engine) DebugRule(ctx context.Context, target, ruleID string, opts ...ScanOption) (*RuleDebug, error)

DebugRule 按扫描的方式对 target 只执行规则 ruleID,返回每条子规则的表达式结果、 交换记录、证据、输出与失败原因。入口跳转链、请求缓存、网络策略与求值规则都与 Scan 相同,结论与扫描一致;调试总是采集证据,结果不交给 Writer。 opts 中的 ScanNetworkPolicy、ScanEvaluationReport 与 ScanObserver 同样生效。

func (*Engine) FingerCount

func (e *Engine) FingerCount() int

FingerCount 当前加载的指纹规则数量。

func (*Engine) GetBaseInfo

func (e *Engine) GetBaseInfo(ctx context.Context, target string) (*BaseInfo, error)

GetBaseInfo 仅获取目标基础信息(不执行指纹匹配)。

func (*Engine) IsClosed

func (e *Engine) IsClosed() bool

IsClosed 引擎是否已 Close。

func (*Engine) LoadFingerOptions

func (e *Engine) LoadFingerOptions(opts FingerOptions) error

LoadFingerOptions 运行期重新加载指纹规则。

func (*Engine) NormalizeURL

func (e *Engine) NormalizeURL(ctx context.Context, target string) (string, error)

NormalizeURL 规范化目标地址(http / https 自动探测)。

func (*Engine) PoolStats

func (e *Engine) PoolStats() PoolStats

PoolStats 规则池统计快照。

func (*Engine) RuleCatalog added in v1.2.0

func (e *Engine) RuleCatalog(ctx context.Context) ([]RuleMetadata, error)

RuleCatalog 返回全部规则的元数据、检测条件和待核对字段,适用于系统导入。

func (*Engine) Scan

func (e *Engine) Scan(ctx context.Context, target string) (*TargetResult, error)

Scan 对单个目标执行完整指纹识别。

扫描结果在返回调用方之前会先送入 Writer;Writer 失败仅记录日志, 不影响 Scan 的返回值,调用方仍能拿到完整的 *TargetResult。

func (*Engine) ScanBatch

func (e *Engine) ScanBatch(ctx context.Context, targets []string) ([]*TargetResult, error)

ScanBatch 批量扫描目标,等待所有目标完成后一次性返回结果列表。

func (*Engine) ScanCallback

func (e *Engine) ScanCallback(ctx context.Context, targets []string, cb TargetCallback) error

ScanCallback 对一批目标执行流式扫描。 每完成一个目标立即调用 cb;cb 返回 false 时通过派生 context 取消后续派发与进行中的 ScanTarget。

func (*Engine) ScanIterator

func (e *Engine) ScanIterator(ctx context.Context, targets iter.Seq[string], cb TargetCallback) error

ScanIterator 按并发预算从迭代器拉取目标,完成后串行调用 cb。 迭代器须遵守 yield 返回 false 即停止的约定,并自行处理输入源的取消。 不保留成功结果;目标错误按 ScanCallback 的约定聚合返回。

func (*Engine) ScanWith added in v1.8.0

func (e *Engine) ScanWith(ctx context.Context, target string, opts ...ScanOption) (*TargetResult, error)

ScanWith 与 Scan 相同,并应用本次扫描的附加配置。未传任何选项时与 Scan 完全一致。

func (*Engine) WappalyzerScan

func (e *Engine) WappalyzerScan(ctx context.Context, target string) (*TechStack, error)

WappalyzerScan 仅做技术栈识别。

type EvaluationFailure added in v1.8.0

type EvaluationFailure = runner.EvaluationFailure

EvaluationFailure 是一处使结论不完整的原因。Message 是有界文本(最多 256 字节),不含响应正文。

type EvaluationReport added in v1.8.0

type EvaluationReport = runner.EvaluationReport

EvaluationReport 报告一次扫描中每条规则是否完整求值。它不改变普通匹配语义,只说明 结论是否完整:Complete 为 true 表示全部规则都已执行且没有任何失败;Truncated 表示 记录超出上限(每条规则 16 条失败、每次扫描 65536 条规则)而被省略,此时 Complete 为 false。

type Exchange added in v1.8.0

type Exchange = network.Exchange

Exchange 是一次请求与响应的记录,字段说明见 network.Exchange。

type ExchangeLimits added in v1.8.0

type ExchangeLimits = network.ExchangeLimits

ExchangeLimits 限制交换记录的大小与数量;零值字段取默认值(正文 64 KiB、 请求头与响应头各 64 KiB、每次扫描 10000 条),MaxBody、MaxHeader 为负数时不复制。

type FailureStage added in v1.8.0

type FailureStage = runner.FailureStage

FailureStage 是规则求值不完整的原因:request(请求失败)、expression(表达式运行错误)、 non_bool(结果不是布尔值)、extract(输出提取失败)、regex_timeout(正则匹配超时, 按未命中处理)、panic(求值 panic)、budget(正文截断、计算成本或记录超出上限)。

type FingerInfo

type FingerInfo struct {
	ID                 string         `json:"id"`
	Name               string         `json:"name"`
	Author             string         `json:"author,omitempty"`
	Severity           string         `json:"severity,omitempty"`
	Description        string         `json:"description,omitempty"`
	Tags               []string       `json:"tags,omitempty"`
	Vendor             string         `json:"vendor,omitempty"`
	Verified           *bool          `json:"verified"`
	VerificationStatus string         `json:"verification_status"`
	Confidence         *float64       `json:"confidence"`
	References         []string       `json:"references,omitempty"`
	Created            string         `json:"created,omitempty"`
	Source             RuleSource     `json:"source"`
	Product            *ProductInfo   `json:"product,omitempty"`
	Validation         ValidationInfo `json:"validation"`
	// Services 是规则声明的 TCP/UDP 服务;HTTP 规则通常为空。
	Services []Service `json:"services,omitempty"`
	// Metadata 是规则 info.metadata 的副本,引擎只透传,不参与匹配。
	Metadata map[string]any `json:"metadata,omitempty"`
}

FingerInfo 指纹规则元信息。

type FingerMatch

type FingerMatch struct {
	Info             FingerInfo     `json:"info"`
	Result           bool           `json:"result"`
	Expression       string         `json:"expression"`
	ProductVersion   string         `json:"product_version,omitempty"`
	ProductVersions  []string       `json:"product_versions,omitempty"`
	VersionConflict  bool           `json:"version_conflict,omitempty"`
	DetailsTruncated bool           `json:"details_truncated,omitempty"`
	MatchedRules     []SubRuleMatch `json:"matched_rules,omitempty"`
}

FingerMatch 单条指纹匹配结果。

type FingerOptions

type FingerOptions struct {
	PocFile string // 指纹规则目录路径
	PocYaml string // 单个 YAML 文件路径
}

FingerOptions 指纹规则加载选项(独立类型,不暴露内部 types 包)。

func NewFingerOptions

func NewFingerOptions() (FingerOptions, error)

NewFingerOptions 自动探测当前目录的 fingerYaml/,如果存在则用它,否则返回空 FingerOptions (Engine 会自动 fallback 到嵌入式指纹库)。

type IconEvidence added in v1.8.0

type IconEvidence struct {
	URL         string `json:"url"`
	ContentType string `json:"content_type,omitempty"`
	Bytes       int64  `json:"bytes"`
	SHA256      string `json:"sha256"`
	MMH3        string `json:"mmh3"`
	Data        []byte `json:"data,omitempty"`
	TooLarge    bool   `json:"too_large,omitempty"`
	CrossOrigin bool   `json:"cross_origin,omitempty"`
}

IconEvidence 是最终页面图标的证据,来自计算 icon_hash 的同一次真实请求,不另发请求。 MMH3 与 response.icon_hash 相同;Data 是图标原始字节,超过 WithIconEvidence 的上限时 为空并置 TooLarge;CrossOrigin 表示图标与页面不属于同一资产。图标地址是 data URL 时 URL 只保留媒体类型部分。

type MatchEvidence added in v1.2.0

type MatchEvidence cel.Evidence

MatchEvidence 是实际求值分支的证据,位置使用原字段的字节区间。

type MultiWriter

type MultiWriter struct {
	// contains filtered or unexported fields
}

MultiWriter 把多个 Writer 串行组合,写入按注册顺序依次触发, 单个 writer 错误会被收集到 errors.Join 中返回,不影响后续 writer。

func NewMultiWriter

func NewMultiWriter(writers ...Writer) *MultiWriter

NewMultiWriter 用一组 Writer 构造 MultiWriter,nil 元素会被忽略。

func (*MultiWriter) Close

func (m *MultiWriter) Close() error

Close 关闭所有底层 Writer 并收集错误。

func (*MultiWriter) Write

func (m *MultiWriter) Write(ctx context.Context, result *TargetResult) error

Write 依次调用底层 Writer.Write,收集全部 error 后统一返回。

type NetworkPolicy added in v1.8.0

type NetworkPolicy = network.Policy

NetworkPolicy 约束引擎的全部出站连接:HTTP、Raw HTTP、TCP、UDP、图标、附属资源、 跳转、TLS 探测与代理健康探测。各字段为 nil 时保持默认行为,字段说明见 network.Policy。

type Option

type Option func(*engineConfig) error

Option 配置 Engine 的函数式选项。

用法:

engine, err := sdk.NewEngine(ctx,
    sdk.WithTimeout(15 * time.Second),
    sdk.WithProxy("http://127.0.0.1:8080"),
    sdk.WithRuleConcurrency(500),
)

func WithBodyLimit added in v1.8.0

func WithBodyLimit(n int64) Option

WithBodyLimit 设置响应正文的读取上限(默认 512 KiB),作用于入口页面、规则请求 (含 Raw HTTP)与附属资源。超出部分不读取,规则按截断后的内容求值;求值报告中 使用了截断响应的子规则记为 budget。

func WithCacheMaxBytes added in v1.8.0

func WithCacheMaxBytes(n int64) Option

WithCacheMaxBytes 设置请求/响应缓存的字节预算(默认 64 MiB)。超出单条预算的响应 不进入缓存,需要它的规则各自重新请求;预算只影响请求次数,不影响识别结论。

func WithCacheSize

func WithCacheSize(size int) Option

WithCacheSize 设置请求/响应缓存最大条目数(默认 2048)。

func WithCacheTTL

func WithCacheTTL(ttl time.Duration) Option

WithCacheTTL 设置请求缓存条目的 TTL(默认 10 分钟)。

注意:请求缓存按单次 Scan 作用域隔离,扫描结束即清理,因此 TTL 实际只约束 同一次扫描内(通常亚秒级)的条目存活。它不是跨扫描的缓存,调大 TTL 不会让 不同次扫描复用响应;此选项主要为长耗时单目标扫描预留。

func WithCustomHeaders

func WithCustomHeaders(headers map[string]string) Option

WithCustomHeaders 设置当前实例的自定义请求头。

func WithDebug

func WithDebug(enable bool) Option

WithDebug 启用调试日志(仅影响日志详细程度,不改变扫描行为)。 未调用 logger.InitLogger 时同样生效。

func WithDisableKeepAlives

func WithDisableKeepAlives(disable bool) Option

WithDisableKeepAlives 是否禁用 HTTP Keep-Alive。 默认 false(启用 Keep-Alive),仅在遇 "Unsolicited response" 等兼容性问题时显式关闭。

func WithFingerOptions

func WithFingerOptions(opts FingerOptions) Option

WithFingerOptions 指定指纹规则文件 / 目录路径。 若为空则使用嵌入式指纹库。

func WithGlobalRateLimit added in v1.6.0

func WithGlobalRateLimit(perSecond float64, burst int) Option

WithGlobalRateLimit 限制引擎发出的全部请求的总速率(次/秒),默认不限制。

入口请求、规则请求、TCP/UDP 请求、图标以及重定向的每一跳都计入。burst 是瞬时 突发上限,传 1 表示严格匀速。可与 WithRateLimit 同时使用:请求先等待总速率的 名额,再等待目标主机的名额。

func WithGlobalRatePerMinute added in v1.6.0

func WithGlobalRatePerMinute(perMinute int) Option

WithGlobalRatePerMinute 按每分钟请求数限制引擎的总速率,请求匀速发出。 等价于 WithGlobalRateLimit(perMinute/60, 1)。

func WithIconEvidence added in v1.8.0

func WithIconEvidence(maxData int) Option

WithIconEvidence 在 TargetResult.Icon 中记录最终页面图标的证据:地址、类型、字节数、 SHA256、MMH3,以及不超过 maxData 字节的原始数据(maxData 为 0 时不保存原始数据)。 证据来自计算 icon_hash 的同一次真实请求,不再二次请求;同一引擎内命中图标缓存时 证据随缓存复用。默认关闭。

func WithInsecureSkipVerify

func WithInsecureSkipVerify(skip bool) Option

WithInsecureSkipVerify 是否跳过 TLS 证书验证(默认 true,扫描场景普遍需要)。

func WithJARM added in v1.8.0

func WithJARM(enable bool) Option

WithJARM 为 HTTPS 目标计算 JARM 指纹,写入 TargetResult.TLS.JARM 与表达式变量 response.jarm。默认关闭。

JARM 按公开算法向最终页面所在的主机端口依次发送 10 个构造的 ClientHello 并解析 响应,每个探测是一次独立连接,经过网络策略(CheckTarget、Dial、代理)与限速; 目标没有以 TLS 响应或探测超时时为 62 个 0。

func WithLogger

func WithLogger(log *slog.Logger) Option

WithLogger 注入实例独立的标准库日志器。未配置时 SDK 不输出日志。

func WithMatchDetails added in v1.2.0

func WithMatchDetails(enabled bool) Option

WithMatchDetails 控制命中子规则与证据回传;产品版本和元数据始终保留。

func WithMemoryMonitor

func WithMemoryMonitor(enable bool) Option

WithMemoryMonitor 启用内存监控(默认关闭)。

func WithMemoryThresholds

func WithMemoryThresholds(highBytes, criticalBytes uint64) Option

WithMemoryThresholds 设置内存高位 / 临界阈值(字节)。

func WithNetworkPolicy added in v1.8.0

func WithNetworkPolicy(policy NetworkPolicy) Option

WithNetworkPolicy 设置引擎级网络策略,作用于该引擎的全部扫描与基础信息请求。

Dial 替代直连拨号,配置代理时用于连接代理服务器本身;CheckTarget 在每次发往目标之前 调用(含重试、跳转与经代理隧道的目标),返回错误即拒绝且不会有任何字节发往该目标; Redirect 可以阻止跟随 30x、刷新与脚本跳转,不访问的地址记入 RedirectTo; WrapTransport 包装 HTTP 请求的底层 RoundTripper。

func WithOutputFile

func WithOutputFile(path string, format OutputFormat) Option

WithOutputFile 把每个完成扫描的目标结果写入本地文件。

  • path: 目标文件路径,父目录会被自动创建,空字符串表示不启用;
  • format: txt / csv / json,未知值回退到 txt。

内部使用实例化的 FileWriter(自带异步队列),多 Engine 互不影响。

func WithProactiveGC

func WithProactiveGC(enable bool) Option

WithProactiveGC 启用主动 GC(默认关闭,避免 STW 放大尾延迟)。

func WithProductCatalog added in v1.2.0

func WithProductCatalog(products []ProductDefinition) Option

WithProductCatalog 按明确的规则 ID 追加或覆盖产品声明:列出的规则没有声明时追加,已有 声明时以目录为准,未列出的规则保留自带声明;不从规则作者推测厂商。同一规则出现在两个 目录项中返回 ErrInvalidOption。覆盖已有产品 ID 时应列出它的全部规则,否则同一产品的 声明不一致,加载时返回 ProductConflictError。参数及每个 Engine 的配置均使用独立副本。

func WithProxy

func WithProxy(proxy string) Option

WithProxy 设置 HTTP/HTTPS/SOCKS5 代理地址,空字符串表示不使用代理。

func WithRateLimit

func WithRateLimit(qps float64, burst int) Option

WithRateLimit 启用每主机速率限制,默认不限制。

参数:

  • qps: 每台主机每秒允许的请求数(令牌产生速率)
  • burst: 令牌桶容量(瞬时突发上限)

主机按主机名或 IP 区分,不区分端口:同一台主机上的多个资产共用一个令牌桶。 需要每个端口各自限速时配合 WithRateLimitPerPort(true)。

func WithRateLimitPerPort added in v1.6.1

func WithRateLimitPerPort(enable bool) Option

WithRateLimitPerPort 设置每主机限速的粒度,需与 WithRateLimit 一起使用。

默认 false:按主机名或 IP 限速,同一主机的 80、443、8080 共用一个令牌桶, 限制的是这台主机承受的总速率。true:按“主机:端口”限速,每个端口各有一个 令牌桶,适合同一主机上各端口是互不相干的服务的场景。

func WithResources added in v1.8.0

func WithResources(opts ResourceOptions) Option

WithResources 读取最终页面所在资产的附属资源,写入 TargetResult.Resources,默认全关。 只请求与最终页面同一资产(协议、主机、端口)的地址,只跟随指向同一站点的跳转, 请求经过网络策略与限速,交换观察器记为 resource 记录。

func WithResponseCacheBudget added in v1.8.0

func WithResponseCacheBudget(n int64) Option

WithResponseCacheBudget 设置每次扫描中响应归一化结果(小写化、字符缓冲与预筛选位图) 的估算预算(默认 8 MiB)。超出后按需重新计算,只影响耗时,不影响识别结论。

func WithReverseConfig

func WithReverseConfig(config ReverseConfig) Option

WithReverseConfig 按值设置反连服务,多个 Engine 的查询配置互不影响。

func WithRuleAssessments added in v1.2.0

func WithRuleAssessments(assessments []RuleAssessment) Option

WithRuleAssessments 提供带规则摘要的样本测试记录或校准置信度。 测试记录只作用于完全相同的规则内容。

func WithRuleConcurrency

func WithRuleConcurrency(n int) Option

WithRuleConcurrency 设置规则识别并发上限(默认 200)。 纯匹配与慢网络请求的最佳并发不同,应按实际负载测量。

func WithRuleFS added in v1.8.0

func WithRuleFS(fsys fs.FS, root string) Option

WithRuleFS 从文件系统 fsys 的 root 目录加载全部 .yaml/.yml 规则,可用于内存文件系统 (如 fstest.MapFS)或 embed.FS;root 为 "" 或 "." 表示根目录。规则来源路径相对于 root。 不能与 WithFingerOptions 指定的目录或文件同时使用。

func WithRulePolicy added in v1.8.0

func WithRulePolicy(policy RulePolicy) Option

WithRulePolicy 设置规则策略:加载(含 LoadFingerOptions 重新加载)时逐条检查, 违反即返回错误(errors.Is(err, ErrRulePolicy)),错误中含规则标识与字段。 内置规则库同样受检查。

func WithRuleSourceVersion added in v1.2.0

func WithRuleSourceVersion(version string) Option

WithRuleSourceVersion 声明外部规则包的版本,不影响 SDK 的版本。

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout 设置请求超时时间,必须 > 0。

func WithURLConcurrency

func WithURLConcurrency(n int) Option

WithURLConcurrency 设置 URL 处理并发数(默认 5)。

func WithWriter

func WithWriter(w Writer) Option

WithWriter 注入自定义 Writer(可调用多次累加), 与 WithOutputFile 同时使用时会被合并到 MultiWriter。

type OutputFormat

type OutputFormat string

OutputFormat 列举 FileWriter 支持的写出格式。

const (
	// FormatTXT 人类可读文本,单条记录用分隔线拼接。
	FormatTXT OutputFormat = "txt"
	// FormatCSV 标准 CSV,带 UTF-8 BOM 表头。
	FormatCSV OutputFormat = "csv"
	// FormatJSON 每行一条 JSON Lines。
	FormatJSON OutputFormat = "json"
)

type PoolStats

type PoolStats struct {
	TotalTasks     int64 `json:"total_tasks"`
	CompletedTasks int64 `json:"completed_tasks"`
	FailedTasks    int64 `json:"failed_tasks"`
}

PoolStats 规则池统计信息。

type ProductConflictError added in v1.8.0

type ProductConflictError = finger.ProductConflictError

ProductConflictError 表示同一产品标识在两条规则中的有效声明(规则声明叠加 WithProductCatalog 的覆盖)不一致。NewEngine 与 LoadFingerOptions 返回的错误可用 errors.As 取得它。

type ProductDefinition added in v1.2.0

type ProductDefinition struct {
	ProductInfo
	RuleIDs []string `json:"rule_ids"`
}

ProductDefinition 是产品目录的一项:产品信息与声明它的规则标识。

func ProductCatalog added in v1.2.0

func ProductCatalog() ([]ProductDefinition, error)

ProductCatalog 返回内置产品目录的独立副本,便于系统扩展及导入。目录由内置规则的 产品声明生成,每个产品列出声明它的全部规则标识。

type ProductInfo added in v1.2.0

type ProductInfo struct {
	ID          string   `json:"id"`
	Name        string   `json:"name"`
	Vendor      string   `json:"vendor,omitempty"`
	Category    string   `json:"category,omitempty"`
	Identity    string   `json:"identity,omitempty"`
	Assurance   string   `json:"assurance,omitempty"`
	Tags        []string `json:"tags,omitempty"`
	Aliases     []string `json:"aliases,omitempty"`
	CPE         []string `json:"cpe,omitempty"`
	References  []string `json:"references,omitempty"`
	Description string   `json:"description,omitempty"`
}

ProductInfo 是规则命中的产品,来自规则的 info.product 声明,或 WithProductCatalog 对该规则 的覆盖;未知厂商、CPE 和分类不从名称自动推断。Identity 为 product 表示命中即确认是这个 产品,signal 表示只是技术线索;Assurance 为 verified 表示厂商与产品已确认且有官方参考 链接,inferred 表示由规则名称与特征推断。

type ProductMatch added in v1.2.0

type ProductMatch struct {
	ProductInfo
	Version         string   `json:"version,omitempty"`
	Versions        []string `json:"versions,omitempty"`
	VersionConflict bool     `json:"version_conflict,omitempty"`
	RuleIDs         []string `json:"rule_ids"`
}

ProductMatch 按目录 ID 归并同一产品,保留每个命中规则的来源。 版本冲突时 Version 留空,并在 Versions 中保留各自结果。

type Redirect added in v1.5.0

type Redirect struct {
	Type     string `json:"type"`             // http(30x)/ refresh(Refresh 头或 meta)/ javascript
	Status   int32  `json:"status,omitempty"` // 发出跳转的响应的状态码
	From     string `json:"from"`
	To       string `json:"to"`
	Followed bool   `json:"followed"` // false:页面里识别出的跳转指向其他资产,没有访问
}

Redirect 入口跳转链上的一跳。

type RedirectAction added in v1.8.0

type RedirectAction = network.RedirectAction

RedirectAction 是 NetworkPolicy.Redirect 对一次跳转的决定。

type RequestKind added in v1.8.0

type RequestKind = network.RequestKind

RequestKind 是一次出站连接的用途。

type Resource added in v1.8.0

type Resource struct {
	Kind       string `json:"kind"`
	URL        string `json:"url"`
	StatusCode int    `json:"status_code"`
	Body       []byte `json:"body,omitempty"`
	BodyBytes  int64  `json:"body_bytes"`
	SHA256     string `json:"sha256"`
	Truncated  bool   `json:"truncated,omitempty"`
}

Resource 是一个附属资源。Kind 为 "robots" 或 "sitemap";URL 是跟随同站跳转后的地址。 Body 是正文的前 MaxBytes 字节;BodyBytes 与 SHA256 覆盖实际读取的正文(受 WithBodyLimit 约束);Truncated 表示 Body 短于实际正文,或正文超过读取上限。请求失败的资源不出现。

type ResourceOptions added in v1.8.0

type ResourceOptions = runner.ResourceOptions

ResourceOptions 选择要读取的附属资源:Robots 读取 /robots.txt,Sitemap 读取 /sitemap.xml;MaxBytes 是每个资源保留的正文上限,0 表示 64 KiB。

type ReverseConfig

type ReverseConfig = types.ReverseConfig

ReverseConfig 描述当前 Engine 的 Ceye 与 JNDI 反连服务。

type RuleAssessment added in v1.2.0

type RuleAssessment struct {
	RuleID     string         `json:"rule_id"`
	RuleSHA256 string         `json:"rule_sha256"`
	Validation ValidationInfo `json:"validation"`
	Confidence *float64       `json:"confidence"`
}

type RuleDebug added in v1.8.0

type RuleDebug struct {
	Match      *FingerMatch   `json:"match,omitempty"`
	SubRules   []SubRuleDebug `json:"sub_rules"`
	Evaluation RuleEvaluation `json:"evaluation"`
}

RuleDebug 是单条规则的调试结果。Match 为 nil 表示未命中。入口跳转链上有多页时, SubRules 描述决定结果的那次评估:命中的那一页,未命中时为最后一页。

type RuleEvaluation added in v1.8.0

type RuleEvaluation = runner.RuleEvaluation

RuleEvaluation 是一条规则的求值情况:Completed 为 true 表示每个子规则都取得了响应并 正常求值,Matched 与普通扫描的命中结果一致。SourceSHA256 是规则文件内容的摘要。

type RuleMetadata added in v1.2.0

type RuleMetadata struct {
	Info            FingerInfo      `json:"info"`
	Transport       string          `json:"transport"`
	Expression      string          `json:"expression"`
	Detection       []DetectionRule `json:"detection"`
	MissingMetadata []string        `json:"missing_metadata,omitempty"`
}

type RulePolicy added in v1.8.0

type RulePolicy = finger.RulePolicy

RulePolicy 限制引擎可以加载的规则。零值表示不限制;任一字段非零时策略生效, 未允许的能力一律拒绝:

  • AllowTypes 为空时允许 http、tcp、udp 全部类型,否则只允许列出的类型;
  • AllowRaw 允许 Raw HTTP 请求;
  • AllowReverse 允许反连检测(set 中的 newReverse()/newJNDI(),表达式中的 wait、jndi);
  • AllowSleep 允许表达式调用 sleep;
  • MaxRules、MaxSubRules 限制规则数与单条规则的子规则数,0 表示不限制。

只允许 HTTP、其余全部禁止可以写成 RulePolicy{AllowTypes: []string{"http"}}; 允许全部类型但禁止 raw、反连与 sleep 可以写成 RulePolicy{AllowTypes: []string{"http", "tcp", "udp"}}。

type RulePolicyError added in v1.8.0

type RulePolicyError = finger.PolicyError

RulePolicyError 是一处违反规则策略的内容,含规则标识与字段路径(如 rules.r0.request.raw)。 NewEngine 与 LoadFingerOptions 返回的错误可用 errors.As 取得它。

type RuleSource added in v1.2.0

type RuleSource struct {
	Path    string `json:"path"`
	SHA256  string `json:"sha256"`
	Version string `json:"version,omitempty"`
}

type ScanOption added in v1.8.0

type ScanOption func(*scanConfig)

ScanOption 配置一次 ScanWith 或 DebugRule。

func ScanEvaluationReport added in v1.8.0

func ScanEvaluationReport(dst *EvaluationReport) ScanOption

ScanEvaluationReport 在扫描结束后(含失败与取消)把求值报告写入 dst,覆盖其原有内容。

func ScanNetworkPolicy added in v1.8.0

func ScanNetworkPolicy(policy NetworkPolicy) ScanOption

ScanNetworkPolicy 设置本次扫描的网络策略,逐字段覆盖引擎级策略:非 nil 的字段替换 引擎级的同名字段,nil 字段沿用引擎级。

设置了 Dial 时,本次扫描的 HTTP 连接不进入连接池,不同扫描的拨号互不混用; 已缓存的 Transport 照常复用,不为每次扫描新建 Transport。

func ScanObserver added in v1.8.0

func ScanObserver(observe func(Exchange), limits ExchangeLimits) ScanOption

ScanObserver 在本次扫描的每次交换完成后回调 observe:入口与跳转、规则请求(HTTP、 Raw、TCP、UDP)、图标、附属资源与 TLS 探测;规则复用本次扫描已有响应时回调一条 Cached 记录。回调在发出请求的协程中串行执行,Sequence 按回调顺序递增;记录中的 切片与映射只读,需要保留时自行复制。并发的多次扫描各自回调,互不串扰。

type ServerInfo

type ServerInfo struct {
	OriginalServer string `json:"original_server"`
	ServerType     string `json:"server_type"`
	Version        string `json:"version"`
}

ServerInfo 服务器信息。

type Service added in v1.8.0

type Service struct {
	Protocol  string `json:"protocol"`
	Transport string `json:"transport"`
	Ports     []int  `json:"ports,omitempty"`
}

Service 是 TCP/UDP 规则识别的服务,来自规则的 info.services。

type SubRuleDebug added in v1.8.0

type SubRuleDebug struct {
	Key        string             `json:"key"`
	Expression string             `json:"expression"`
	Result     *bool              `json:"result"`
	Exchanges  []Exchange         `json:"-"`
	Evidence   []MatchEvidence    `json:"evidence,omitempty"`
	Outputs    map[string]string  `json:"outputs,omitempty"`
	Failure    *EvaluationFailure `json:"failure,omitempty"`
}

SubRuleDebug 是单条子规则的中间结果。Result 为 nil 表示没有得到布尔结论(请求失败、 表达式出错或扫描取消);Exchanges 是该子规则使用的交换记录,复用已有响应时为 Cached 记录。

type SubRuleMatch added in v1.2.0

type SubRuleMatch struct {
	Key               string            `json:"key"`
	Expression        string            `json:"expression"`
	Method            string            `json:"method"`
	Path              string            `json:"path"`
	URL               string            `json:"url"`
	StatusCode        int32             `json:"status_code"`
	Evidence          []MatchEvidence   `json:"evidence,omitempty"`
	EvidenceTruncated bool              `json:"evidence_truncated,omitempty"`
	Outputs           map[string]string `json:"outputs,omitempty"`
}

type TLSInfo added in v1.8.0

type TLSInfo struct {
	Version     string `json:"version"`        // 如 "TLS 1.2"
	CipherSuite string `json:"cipher_suite"`   // 如 "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
	ALPN        string `json:"alpn,omitempty"` // 协商的应用层协议
	JA3S        string `json:"ja3s,omitempty"` // ServerHello 的 JA3S 摘要
	JARM        string `json:"jarm,omitempty"` // 62 位 JARM 指纹;全零表示目标没有以 TLS 响应
}

TLSInfo 是一次 TLS 握手的摘要。版本、套件、ALPN 与 JA3S 取自扫描本来就有的那次 握手:握手期间旁路记录服务端的 ServerHello,按公开的 JA3S 定义计算,不增加连接。 JARM 需要另外发送 10 个构造的 ClientHello,只在 WithJARM(true) 时计算。

type TargetCallback

type TargetCallback func(result *TargetResult) bool

TargetCallback 流式回调签名。 每完成一个目标立即触发 cb;返回 false 时取消尚未开始或进行中的后续扫描。

type TargetRequest added in v1.8.0

type TargetRequest = network.TargetRequest

TargetRequest 描述一次即将发往目标的连接,供 NetworkPolicy.CheckTarget 判断。

type TargetResult

type TargetResult struct {
	URL        string         `json:"url"`
	FinalURL   string         `json:"final_url,omitempty"`
	RedirectTo string         `json:"redirect_to,omitempty"`
	Redirects  []Redirect     `json:"redirects,omitempty"`
	StatusCode int32          `json:"status_code"`
	Title      string         `json:"title"`
	Server     *ServerInfo    `json:"server,omitempty"`
	Headers    string         `json:"headers,omitempty"` // 最终页面的原始响应头
	Matches    []FingerMatch  `json:"matches"`
	TechStack  *TechStack     `json:"tech_stack,omitempty"`
	ICP        string         `json:"icp,omitempty"`
	Certs      []CertInfo     `json:"certs,omitempty"`
	Products   []ProductMatch `json:"products,omitempty"`
	// HeaderOrder 是最终页面的响应头名称,按服务器返回的顺序,保留重复与原始大小写。
	HeaderOrder []string `json:"header_order,omitempty"`
	// TLS 是最终页面所在连接的握手摘要;明文目标为 nil。
	TLS *TLSInfo `json:"tls,omitempty"`
	// Icon 是最终页面图标的证据,WithIconEvidence 开启且页面有图标时非空。
	Icon *IconEvidence `json:"icon,omitempty"`
	// Resources 是最终页面所在资产的附属资源(robots.txt、sitemap.xml),WithResources 开启时读取。
	Resources []Resource `json:"resources,omitempty"`
	// Error 由调用方在目标扫描失败时填写,用于把失败原因随结果一起输出;
	// Scan 成功返回的结果中始终为空。
	Error string `json:"error,omitempty"`
}

TargetResult 单个目标的完整扫描结果。

一个目标由协议、主机、端口确定。入口的 HTTP 30x 总是跟随(可以指向其他主机), FinalURL 是跳转链最后一页的地址,StatusCode、Title、TechStack、ICP 描述该页面。 页面里识别出的跳转(meta refresh、脚本)只在当前页所在的资产内跟随,指向其他 资产时不访问,地址记入 RedirectTo。

type TechStack

type TechStack struct {
	WebServers           []string `json:"web_servers,omitempty"`
	ReverseProxies       []string `json:"reverse_proxies,omitempty"`
	JavaScriptFrameworks []string `json:"java_script_frameworks,omitempty"`
	JavaScriptLibraries  []string `json:"java_script_libraries,omitempty"`
	WebFrameworks        []string `json:"web_frameworks,omitempty"`
	StaticSiteGenerator  []string `json:"static_site_generator,omitempty"`
	ProgrammingLanguages []string `json:"programming_languages,omitempty"`
	Caching              []string `json:"caching,omitempty"`
	Security             []string `json:"security,omitempty"`
	HostingPanels        []string `json:"hosting_panels,omitempty"`
	CMS                  []string `json:"cms,omitempty"`
	Databases            []string `json:"databases,omitempty"`
	Ecommerce            []string `json:"ecommerce,omitempty"`
	CDN                  []string `json:"cdn,omitempty"`
	Analytics            []string `json:"analytics,omitempty"`
	OperatingSystems     []string `json:"operating_systems,omitempty"`
	Other                []string `json:"other,omitempty"`
}

TechStack 站点技术栈信息。命名字段覆盖高价值分类,其余识别结果归入 Other,不丢弃。

type ValidateOptions added in v1.8.0

type ValidateOptions struct {
	Strict bool
	Policy RulePolicy
}

ValidateOptions 是 ValidateRule 的选项。Strict 为 true 时规范性问题(未知键、缺少 必填信息、产品与服务声明不合规、表达式无法编译)报告为 error,否则为 warning; Policy 与 WithRulePolicy 相同。

type ValidationInfo added in v1.2.0

type ValidationInfo struct {
	Status          string `json:"status"`
	Method          string `json:"method,omitempty"`
	PositiveSamples int    `json:"positive_samples,omitempty"`
	NegativeSamples int    `json:"negative_samples,omitempty"`
	ReviewedAt      string `json:"reviewed_at,omitempty"`
	Scope           string `json:"scope,omitempty"`
}

ValidationInfo 描述测试方法和样本范围,不把有限样本测试当作实际准确率。

type Writer

type Writer interface {
	Write(ctx context.Context, result *TargetResult) error
	Close() error
}

Writer 是 SDK 把 *TargetResult 持久化或转发出去的抽象。

内置实现:FileWriter / SockWriter / MultiWriter / NopWriter。 调用方也可自行实现该接口(如对接 Kafka、Webhook 等),并通过 sdk.WithWriter(w) 注入到 Engine。

Write 必须满足以下并发与所有权约束:

  • 同一实例可能被多 goroutine 并发调用,实现需自行保证线程安全;
  • Write 收到 nil 时必须直接返回 nil,不得 panic;
  • 即便返回 error,Engine 也只会记录日志,不会终止扫描;
  • result 仅在本次调用期间有效、且与调用方拿到的 *TargetResult 是同一指针: 实现必须把它视为只读,不得修改;若需在 Write 返回后异步使用,必须先自行深拷贝。 内置 FileWriter(异步队列)在入队前已深拷贝,SockWriter 在调用内同步序列化,均安全。

Close 在 Engine.Close 中被调用,实现应释放底层资源并 flush 缓冲; 重复调用必须幂等。

func NewFileWriter

func NewFileWriter(path string, format OutputFormat) (Writer, error)

NewFileWriter 创建一个把 *TargetResult 写到本地文件的 Writer。

  • path: 目标文件路径,父目录会被自动创建;空字符串时返回 NopWriter;
  • format: txt / csv / json,未知值回退到 txt。

已存在的文件会以追加模式打开(CSV 例外:仅在新建时写入 UTF-8 BOM + 表头)。

func NewSockWriter

func NewSockWriter(path string) (Writer, error)

NewSockWriter 创建并监听一个 Unix domain socket, 把每条扫描结果以 JSON Lines 形式广播到所有客户端连接。

path 为空字符串时返回 NopWriter;socket 文件存在时会先删除再重新创建。

func NopWriter

func NopWriter() Writer

NopWriter 返回不执行任何写出动作的 Writer,常用于禁用输出。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL