当前位置: 首页 > news >正文

【安全研发】Nuclei源码分析-模板引擎实现(五)

目录

  • Nuclei 模板引擎实现详解
    • 1. 模板引擎概述
    • 2. 核心数据结构
      • 2.1 Template 结构体
      • 2.2 Executer 接口
      • 2.3 Request 接口
    • 3. 模板引擎工作流程
      • 3.1 模板加载
      • 3.2 模板解析
      • 3.3 模板编译
      • 3.4 模板执行
    • 4. 模板引擎特性
      • 4.1 多协议支持
      • 4.2 工作流支持
      • 4.3 变量和表达式
      • 4.4 缓存机制
    • 5. 核心代码位置
    • 6. 总结

Nuclei 模板引擎实现详解

Nuclei 的模板引擎是其核心组件,负责解析、编译和执行 YAML 格式的模板文件。模板引擎使 Nuclei 能够执行各种协议的漏洞扫描任务。本文将详细分析 Nuclei 模板引擎的实现机制。

1. 模板引擎概述

Nuclei 模板引擎主要由以下几个核心组件构成:

2. 核心数据结构

2.1 Template 结构体

Template (nuclei\v2\pkg\templates\templates.go#L24-L74) 结构体是模板引擎的核心数据结构,定义在 v2/pkg/templates/templates.go 文件中:

type Template struct {
ID              string                 // 模板唯一标识符
Info            model.Info          // 模板元数据信息
RequestsHTTP    []*http.Request     // HTTP 请求定义
RequestsDNS     []*dns.Request      // DNS 请求定义
RequestsFile    []*file.Request         // 文件请求定义
RequestsNetwork []*network.Request  // 网络请求定义
RequestsHeadless []*headless.Request // 无头浏览器请求定义
workflows.Workflow        // 内嵌工作流结构
CompiledWorkflow *workflows.Workflow    // 编译后的工作流
SelfContained bool    // 是否为自包含请求
TotalRequests int      // 模板总请求数
Executer protocols.Executer     // 模板执行器
Path     string      // 模板文件路径
}
type Workflow struct {
Workflows []*WorkflowTemplate
Options *protocols.ExecuterOptions `yaml:"-"`
}

2.2 Executer 接口

Executer(nuclei\v2\pkg\protocols\protocols.go#L15-L22) 接口定义了模板执行器的行为,位于 v2/pkg/protocols/protocols.go:

type Executer interface {
Compile() error  // 编译模板
Requests() int   // 返回请求数量
Execute(input string) (bool, error)  // 执行模板
ExecuteWithResults(input string, callback OutputEventCallback) error
}

2.3 Request 接口

Request (nuclei\v2\pkg\protocols\protocols.go#L47-L62) 接口定义了各种协议请求的行为:

type Request interface {
Compile(options *ExecuterOptions) error
Requests() int
GetID() string
Match(data map[string]interface{}, matcher *matchers.Matcher) (bool, []string)
Extract(data map[string]interface{}, matcher *extractors.Extractor) map[string]struct{}
ExecuteWithResults(input string, dynamicValues, previous output.InternalEvent, callback OutputEventCallback) error
MakeResultEventItem(wrapped *output.InternalWrappedEvent) *output.ResultEvent
MakeResultEvent(wrapped *output.InternalWrappedEvent) []*output.ResultEvent
GetCompiledOperators() []*operators.Operators
}

3. 模板引擎工作流程

3.1 模板加载

模板加载过程由 loader.Store (nuclei\v2\pkg\catalog\loader\loader.go#L30-L40) 类负责,主要步骤包括:

func (store *Store) LoadTemplates(templatesList []string) []*templates.Template {
includedTemplates := store.config.Catalog.GetTemplatesPath(templatesList)
templatePathMap := store.pathFilter.Match(includedTemplates)
loadedTemplates := make([]*templates.Template, 0, len(templatePathMap))
for templatePath := range templatePathMap {
loaded, err := parsers.LoadTemplate(templatePath, store.tagFilter, nil)
if err != nil {
gologger.Warning().Msgf("Could not load template %s: %s\n", templatePath, err)
}
if loaded {
parsed, err := templates.Parse(templatePath, store.preprocessor, store.config.ExecutorOptions)
if err != nil {
gologger.Warning().Msgf("Could not parse template %s: %s\n", templatePath, err)
} else if parsed != nil {
loadedTemplates = append(loadedTemplates, parsed)
}
}
}
return loadedTemplates
}

3.2 模板解析

模板解析由 templates.Parse (nuclei\v2\pkg\templates\compile.go#L33-L141) 函数完成,主要步骤包括:

  • 文件读取 - 读取模板 YAML 文件内容
  • 预处理 - 应用预处理器处理模板内容
  • YAML 解析 - 使用 yaml.Unmarshal 将 YAML 内容解析为 Template 结构体
  • 验证检查 - 验证模板必需字段是否完整
func Parse(filePath string, preprocessor Preprocessor, options protocols.ExecuterOptions) (*Template, error) {
// 从缓存中获取或创建新模板
template := &Template{}
// 读取文件内容
f, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
// 预处理
data = template.expandPreprocessors(data)
if preprocessor != nil {
data = preprocessor.Process(data)
}
// YAML 解析
if err := yaml.Unmarshal(data, template); err != nil {
return nil, err
}
// 验证必需字段
if utils.IsBlank(template.Info.Name) {
return nil, errors.New("no template name field provided")
}
// ... 其他验证
return template, nil
}

3.3 模板编译

模板编译过程在 templates.Parse (fnuclei\v2\pkg\templates\compile.go#L33-L141) 函数中完成,主要包括:

  • 工作流编译 - 如果模板包含工作流定义,则编译工作流
  • 请求编译 - 编译各种协议的请求
  • 执行器创建 - 为模板创建相应的执行器【执行器根据协议而不同,事先定义好的】
// 编译工作流
if len(template.Workflows) > 0 {
compiled := &template.Workflow
compileWorkflow(filePath, preprocessor, &options, compiled, options.WorkflowLoader)
template.CompiledWorkflow = compiled
template.CompiledWorkflow.Options = &options
}
// 编译各种协议请求
if len(template.RequestsHTTP) > 0 {
// 创建 HTTP 请求执行器
template.Executer = executer.NewExecuter(requests, &options)
}
// 编译执行器
if template.Executer != nil {
if err := template.Executer.Compile(); err != nil {
return nil, errors.Wrap(err, "could not compile request")
}
template.TotalRequests += template.Executer.Requests()
}

3.4 模板执行

模板执行由 executer.Executer (nuclei\v2\pkg\protocols\common\executer\executer.go#L11-L14) 类负责,主要步骤包括:

  • 请求执行 - 依次执行模板中的所有请求
  • 结果匹配 - 使用匹配器和提取器处理响应
  • 结果输出 - 将匹配结果输出到指定位置
func (e *Executer) Execute(input string) (bool, error) {
var results bool
dynamicValues := make(map[string]interface{})
previous := make(map[string]interface{})
for _, req := range e.requests {
req := req
err := req.ExecuteWithResults(input, dynamicValues, previous, func(event *output.InternalWrappedEvent) {
// 处理请求结果
if event.OperatorsResult == nil {
return
}
for _, result := range event.Results {
if e.options.IssuesClient != nil {
// 发送结果到问题跟踪系统
}
results = true
_ = e.options.Output.Write(result)
e.options.Progress.IncrementMatched()
}
})
// 错误处理
}
return results, nil
}

4. 模板引擎特性

4.1 多协议支持

Nuclei 模板引擎支持多种协议:

4.2 工作流支持

模板引擎支持复杂的工作流定义,可以编排多个模板的执行顺序和条件:

workflows:
- template: technologies/tech-detect.yaml
subtemplates:
- template: vulnerabilities/specific-vuln.yaml

4.3 变量和表达式

模板引擎支持丰富的变量系统和 DSL 表达式:

  • 内置变量:{{BaseURL}}、{{Hostname}} 等
  • 自定义变量:通过 -var 参数传递
  • 环境变量:通过 -env-vars 启用

4.4 缓存机制

模板引擎使用缓存来提高性能:

var parsedTemplatesCache *cache.Templates
func init() {
parsedTemplatesCache = cache.New()
}

5. 核心代码位置

  • 模板定义:v2/pkg/templates/templates.go
  • 模板解析和编译:v2/pkg/templates/compile.go
  • 执行器实现:v2/pkg/protocols/common/executer/executer.go
  • 协议请求接口:v2/pkg/protocols/protocols.go
  • 模板加载器:v2/pkg/catalog/loader/loader.go
  • 模板解析器:v2/pkg/parsers/parser.go

6. 总结

Nuclei 的模板引擎通过清晰的架构设计和模块化实现,提供了强大而灵活的漏洞扫描能力。其核心特点包括:


by 久违 2025.10.20

http://www.jsqmd.com/news/67255/

相关文章:

  • 软件单元测试入门与实践
  • 2025年12月重庆店面装修推荐:佐森装饰——以“五星工程”点亮山城商业空间
  • 2025年geo优化软件推荐:AI驱动下的排名新利器
  • 2025年12月成都护墙板/全屋定制/定制实木家具/实木衣柜厂家推荐
  • 2025年12月徐州刑事辩护/取保候审/刑事申诉律师,这五家不容错过
  • 2025年12月江苏徐州皮带秤、给煤机、称重给料机、皮带采样机、汽车采样机厂家综合推荐TOP10榜单
  • 消息积压怎么处理
  • 毛孔隐形日常routine:科学疏通与细滑,告别“草莓鼻”与油光脸
  • 完整教程:基于单片机的交流功率测量仪设计与实现
  • 2025年12月江苏徐州金属熔剂、金属添加剂、铝基中间合金厂家综合推荐指南
  • 数据脱敏技术详解:类型、方法与最佳实践
  • 2025年Grok优化排名公司推荐:技术迭代下的精准选择指南
  • 精选!2025年声学成像仪厂家推荐:西安联丰讯声革新运维的领先企业
  • 权威推荐!2025声纹质检厂家TOP3!西安联丰讯声:技术+口碑双优企业
  • 2025 年 12 月 12Cr1MoVG 合金管,15CrMoG 合金管厂家最新推荐,精准检测与稳定性能深度解析
  • 2025年声学AI检测技术新标杆:西安联丰迅声领航麦克风阵列创新之路
  • 2025年环境噪声检测设备厂家权威推荐榜单TOP5:技术驱动下的“机器听觉”新势力
  • 2025年GEO生成引擎优化服务商哪家好?权威推荐与选型指南
  • 2025年下半年江苏徐州金属熔剂、金属添加剂、铝基中间合金厂家推荐榜单:专业解析与选购指南
  • 2025年非标钣金定制优质供应商排行榜单出炉,市面上非标钣金定制哪家好TOP企业引领行业技术新高度
  • Hbase、zookeeper以及虚拟机错误总结
  • 2025年声纹监测厂家权威推荐:联丰迅声领跑工业声学AI检测新赛道
  • 2025年下半年上海CE认证服务商综合实力排行榜与选择指南
  • 2025年下半年上海ISO三体系认证公司权威评测与选择指南
  • 8
  • 2025年国内可靠的化粪池清掏厂家哪家好,化粪池清掏公司永邦环卫满足多元需求
  • 第十一篇:细粒度权限控制(RBAC)
  • 2025 年 12 月 L360N 管线管,L415N 管线管厂家最新推荐,聚焦资质、案例、售后的五家企业深度解读
  • 2025年12月钢板仓源头厂家推荐: 粉煤灰钢板仓,螺旋卷板仓,焊接钢板仓厂家以技术创新赋能物料存储升级
  • 2025 年养老护工服务平台最新推荐榜,聚焦企业服务品质与用户口碑深度解析品牌好的,比较好的,靠谱的,有实力的,可靠的,正规的,专业的,最好的,知名的,优质养老护工服务机构推荐