cweskills

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2026 License: MIT Imports: 16 Imported by: 0

README

CWE Skills

CWE Skills — AI-Native CWE Integration

Go Reference CI Docs

AI-native integration layer for CWE (Common Weakness Enumeration) — four ways to connect: Skills, Go SDK, CLI, and MCP.

🇨🇳 中文文档 · 📖 Documentation


🚀 Four Ways to Integrate

flowchart TB
    subgraph APP["应用层"]
        AI["AI 代理\nClaude/GPT"]
        GO["Go 应用"]
        SH["Shell 脚本"]
        MCP["MCP 工具"]
    end

    subgraph SDK["CWE Skills 集成层"]
        SK["🦾 Skills"]
        GS["🔧 Go SDK"]
        CLI["💻 CLI"]
        MC["MCP Server"]
    end

    subgraph DATA["数据源"]
        API["MITRE REST API"]
        XML["XML 目录"]
        LIST["内置列表\nTop25/OWASP/SANS"]
    end

    AI --> SK --> API & XML & LIST
    GO --> GS --> API & XML & LIST
    SH --> CLI --> API & XML & LIST
    MCP --> MC --> API & XML & LIST

    classDef app fill:#dcfce7,stroke:#16a34a,color:#166534
    classDef sdk fill:#e8f1f8,stroke:#3c6c8f,color:#1d3a4f
    classDef data fill:#ffedd5,stroke:#ea580c,color:#9a3412
    class APP app
    class SDK sdk
    class DATA data
# Method Best For One-Line Setup
1 Skills AI agents (Claude, GPT, etc.) Copy the prompt below
2 Go SDK Go applications & libraries go get github.com/scagogogo/cwe-skills
3 CLI Shell scripts & dev workflows Download from Releases
4 MCP MCP-compatible AI tools go build ./cmd/cwe-mcp

1. Skills — AI Agent Integration

Copy and paste this block into your AI agent's system prompt or skill configuration:

## CWE Skills

You have access to the `cwe` CLI tool for CWE (Common Weakness Enumeration) operations.

### Install
```bash
# Download pre-built binary (Linux/macOS/Windows)
curl -sL https://github.com/scagogogo/cwe-skills/releases/latest/download/cwe-skills_latest_linux_x86_64.tar.gz | tar xz && sudo mv cwe /usr/local/bin/
# Or build from source:
git clone https://github.com/scagogogo/cwe-skills.git && cd cwe-skills && go build -o cwe ./cmd/cwe/ && sudo mv cwe /usr/local/bin/

Core Commands

Command What it does
cwe parse CWE-79 Parse a CWE ID
cwe validate CWE-79 Validate CWE ID format
cwe show CWE-79 Fetch weakness details from MITRE API
cwe wellknown check CWE-79 Check if in Top 25 / OWASP / SANS lists
cwe enum abstraction List valid enumeration values
cwe search --xml <file> --keyword Injection Search offline XML catalog
cwe filter --xml <file> --abstraction Base --status Stable Multi-criteria filter
cwe registry get CWE-79 --xml <file> Get entry from local registry
cwe nav ancestors CWE-79 --xml <file> Navigate relationships offline
cwe nav shortest-path CWE-79 CWE-1 --xml <file> Find shortest path between two CWEs
cwe tree build CWE-1 --xml <file> Build hierarchy tree
cwe stats --xml <file> Statistics from XML catalog

Output

All commands support -o json for structured JSON output. Example: cwe parse CWE-79 -o json

Go SDK

import "github.com/scagogogo/cwe-skills"
id, _ := cweskills.ParseCWEID("CWE-79")
cweskills.IsInTop25(79) // true
client := cweskills.NewAPIClient()
weakness, _ := client.GetWeakness(ctx, 79)

Skill Docs

Progressive capability docs: https://github.com/scagogogo/cwe-skills/tree/main/docs/skills


---

## 2. Go SDK

```mermaid
flowchart LR
    subgraph SRC["数据源"]
        API["MITRE API"]
        XML["XML 目录"]
    end
    subgraph PARSE["解析"]
        AC["APIClient"]
        XP["XMLParser"]
    end
    REG["Registry\n+ 索引"]
    subgraph USE["消费"]
        NAV["Navigator"]
        TREE["BuildTree"]
        SRCH["FindBy*/Filter"]
        SER["MarshalJSON/CSV"]
    end
    API --> AC --> REG
    XML --> XP --> REG
    REG --> NAV & TREE & SRCH & SER

    classDef online fill:#dbeafe,stroke:#2563eb,color:#1e40af
    classDef offline fill:#ffedd5,stroke:#ea580c,color:#9a3412
    classDef core fill:#e8f1f8,stroke:#3c6c8f,color:#1d3a4f
    classDef local fill:#dcfce7,stroke:#16a34a,color:#166534
    class API,AC online
    class XML,XP offline
    class REG core
    class USE local
import (
    "context"
    "github.com/scagogogo/cwe-skills"
)

// Parse & validate CWE IDs
id, _ := cweskills.ParseCWEID("CWE-79")
if cweskills.IsCWEID("CWE-89") { /* valid */ }

// Query MITRE REST API
client := cweskills.NewAPIClient()
defer client.Close()
weakness, _ := client.GetWeakness(context.Background(), 79)
parents, _ := client.GetParents(context.Background(), 79)

// Local registry from XML
registry, _ := cweskills.NewXMLParser().ParseFile("cwec_v4.15.xml")
registry.BuildIndexes()

// Navigate relationships
nav := cweskills.NewNavigator(registry)
ancestors := nav.Ancestors(79)
path := nav.ShortestPath(79, 1)

// Build hierarchy tree
tree := cweskills.BuildTree(registry, 1)
leaves := tree.LeafNodes()

// Search & filter
results := cweskills.FindByKeyword(registry, "Injection")
filtered := cweskills.Filter(results, cweskills.FilterOption{
    Abstraction: cweskills.AbstractionBase,
    Status:      cweskills.StatusStable,
})

// Well-known lists
cweskills.IsInTop25(79)       // true
cweskills.IsInOWASPTop10(79)  // true
cweskills.IsInSANSTop25(79)   // true

// Serialization
jsonData, _ := registry.ExportJSON()
csvData, _ := registry.ExportCSV()

Install: go get github.com/scagogogo/cwe-skills


3. CLI

mindmap
  root((cwe CLI))
    🆔 ID 工具
      parse
      validate
      format
      extract
      compare
    📚 枚举
      enum abstraction
      enum status
      enum relationship
    🏆 知名列表
      wellknown top25
      wellknown owasp
      wellknown sans
      wellknown check
    🌐 API
      show
      relations
      api-version
    🔍 搜索过滤
      search
      filter
      stats
    🗃️ 注册表
      registry load/get
      registry export
    🧭 导航
      nav parents/children
      nav ancestors/descendants
      nav shortest-path
    🌳 树
      tree build
      tree forest
      tree path

Install

From Release (recommended):

# Linux (amd64)
curl -sL https://github.com/scagogogo/cwe-skills/releases/latest/download/cwe-skills_latest_linux_x86_64.tar.gz | tar xz
sudo mv cwe /usr/local/bin/

# macOS (Apple Silicon)
curl -sL https://github.com/scagogogo/cwe-skills/releases/latest/download/cwe-skills_latest_darwin_aarch64.tar.gz | tar xz
sudo mv cwe /usr/local/bin/

# Windows (PowerShell)
Invoke-WebRequest -Uri https://github.com/scagogogo/cwe-skills/releases/latest/download/cwe-skills_latest_windows_x86_64.zip -OutFile cwe.zip
Expand-Archive cwe.zip

From Source:

git clone https://github.com/scagogogo/cwe-skills.git
cd cwe-skills && go build -o cwe ./cmd/cwe/

From Package Managers:

brew install scagogogo/tap/cwe-skills          # Homebrew
scoop install cwe-skills                         # Scoop (Windows)
go install github.com/scagogogo/cwe-skills/cmd/cwe@latest  # Go

Quick Examples

# CWE ID operations
cwe parse CWE-79 89 cwe-352
cwe validate CWE-79 CWE-89
cwe format 79 89 352
cwe extract "Affected by CWE-79 and CWE-89"
cwe compare CWE-79 CWE-89

# Well-known lists
cwe wellknown top25
cwe wellknown owasp
cwe wellknown check CWE-79

# MITRE API (online)
cwe show CWE-79
cwe relations parents CWE-79
cwe api-version

# Local search & filter (offline)
cwe search --xml cwec_latest.xml --keyword Injection --sort name
cwe filter --xml cwec_latest.xml --abstraction Base --status Stable --likelihood High

# Local registry (offline)
cwe registry load --xml cwec_latest.xml
cwe registry get CWE-79 --xml cwec_latest.xml
cwe registry ancestors CWE-79 --xml cwec_latest.xml
cwe registry export --xml cwec_latest.xml --format json

# Local navigation (offline)
cwe nav siblings CWE-79 --xml cwec_latest.xml
cwe nav peers CWE-79 --xml cwec_latest.xml
cwe nav shortest-path CWE-79 CWE-1 --xml cwec_latest.xml
cwe nav is-ancestor CWE-1 CWE-79 --xml cwec_latest.xml
cwe nav depth CWE-79 CWE-1 --xml cwec_latest.xml

# Tree operations (offline)
cwe tree build CWE-1 --xml cwec_latest.xml
cwe tree forest --xml cwec_latest.xml
cwe tree path CWE-79 --xml cwec_latest.xml
cwe tree leaves CWE-1 --xml cwec_latest.xml

# Enumeration types
cwe enum abstraction
cwe enum status
cwe enum relationship

# JSON output on every command
cwe parse CWE-79 -o json
cwe wellknown check CWE-79 -o json

Command Reference

Command Description
cwe version Show version info
cwe parse/validate/format/extract/compare CWE ID utilities
cwe enum <type> List enumeration values
cwe wellknown top25/owasp/sans/check Well-known lists
cwe show [IDs...] Fetch from MITRE API
cwe relations parents/children/ancestors/descendants API relationships
cwe api-version Check MITRE API version
cwe search --xml <file> [flags] Search offline XML
cwe filter --xml <file> [flags] Multi-criteria filter
cwe stats --xml <file> Statistics
cwe registry <subcmd> --xml <file> Registry operations
cwe nav <subcmd> --xml <file> Relationship navigation
cwe tree <subcmd> --xml <file> Tree operations

4. MCP

The cwe-mcp server exposes 20 tools (parse, validate, extract, format, get_weakness, get_ancestors, get_children, get_siblings, build_tree, search_keyword, filter_cwes, etc.) over stdio/SSE for MCP-compatible AI tools like Claude Desktop.

# Build
go build -o cwe-mcp ./cmd/cwe-mcp/

# Run (stdio for local clients)
./cwe-mcp --xml cwec_v4.15.xml

# Run (SSE for remote)
./cwe-mcp --transport http --addr :8080

Configure Claude Desktop (claude_desktop_config.json):

{
  "mcpServers": {
    "cwe-skills": {
      "command": "/path/to/cwe-mcp",
      "args": ["--xml", "/path/to/cwec_v4.15.xml"]
    }
  }
}

MCP integration guide


Skills Documentation

Progressive skill documentation for AI agents and developers — from simple to advanced:

# Skill Description
1 CWE ID Parsing & Validation Parse, validate, format CWE IDs
2 CWE ID Extraction & Comparison Extract from text, compare IDs
3 Well-Known Lists CWE Top 25, OWASP Top 10, SANS Top 25
4 Enumeration Types Abstraction, Status, Relationship types
5 API: Get Weakness Details Fetch from MITRE API
6 API: Relationship Queries Parent/child/ancestor/descendant via API
7 API: Version Check Check MITRE API version
8 Local: Search & Filter Search & multi-criteria filter
9 Local: Registry Operations Load, query, export local data
10 Local: Relationship Navigation Navigate relationships offline
11 Local: Tree Construction Build & traverse hierarchy trees
12 SDK: Serialization JSON, XML, CSV import/export

Full Skills Index

Supported Platforms

Pre-built binaries for 30+ platforms: Linux (amd64/386/arm64/arm/mips/ppc64/s390x/riscv64), macOS (Intel/Apple Silicon), Windows (amd64/386/arm64), FreeBSD, NetBSD, OpenBSD, AIX, Illumos, Solaris.

Features

  • Complete CWE Data Model: Weaknesses, Categories, Views, Compound Elements
  • Typed Enumerations: Abstraction, Status, Relationship, Consequence, View types
  • CWE ID Utilities: Parse, format, validate, extract, compare
  • Well-Known Lists: CWE Top 25, OWASP Top 10, SANS Top 25
  • MITRE REST API Client: Rate limiting, retry, structured errors
  • XML Catalog Parser: Offline MITRE XML parsing
  • In-Memory Registry: Store, index, query with relationship indexes
  • Search & Filter: Keyword, abstraction, status, likelihood, scope, sort, group
  • Relationship Navigation: Parents, children, ancestors, descendants, siblings, peers, chains, composites, shortest path, relationship depth
  • Tree Construction: Build, traverse, find paths, list leaves
  • Serialization: JSON, XML, CSV import/export
  • 40+ CLI Subcommands: Text/JSON dual output
  • Zero Dependencies: Core SDK uses only Go standard library

License

MIT License - see LICENSE for details.

Documentation

Overview

Package cweskills 提供了对CWE(Common Weakness Enumeration,通用缺陷枚举)的完整支持, 包括CWE条目的解析、验证、搜索、过滤、关系导航、树构建、序列化等功能。

本包旨在作为网络安全产品的底层SDK,支持SAST/DAST工具、漏洞管理平台、 合规检查系统等上层应用基于此构建。

主要功能:

  • CWE ID的格式化、解析、验证和提取
  • 完整的枚举类型定义(抽象层级、状态、关系类型等)
  • 结构化错误类型
  • 知名CWE列表(Top 25、OWASP Top 10等)
  • 核心数据模型(Weakness、Category、View、CompoundElement)
  • 关系导航(父/子/祖先/后代/链/组合)
  • 内存注册表与索引
  • 搜索与过滤
  • MITRE CWE REST API客户端
  • XML目录解析(离线模式)
  • JSON/XML/CSV序列化
  • 速率限制的HTTP客户端

示例:

// 解析CWE ID
id, err := cwe.ParseCWEID("CWE-79")
if err != nil {
    log.Fatal(err)
}
fmt.Println(id) // 输出: 79

// 格式化CWE ID
formatted := cwe.FormatCWEID("79")
fmt.Println(formatted) // 输出: CWE-79

// 检查是否为Top 25
if cwe.IsInTop25(79) {
    fmt.Println("CWE-79 is in CWE Top 25")
}

Index

Constants

View Source
const (
	// CWEViewResearchConcepts 研究概念视图 (CWE-1000)
	// 按照抽象概念组织CWE条目的层次结构
	CWEViewResearchConcepts = 1000

	// CWEViewDevelopmentConcepts 软件开发视图 (CWE-699)
	// 按照软件开发活动组织CWE条目
	CWEViewDevelopmentConcepts = 699

	// CWEViewHardwareDesign 硬件设计视图 (CWE-1199)
	// 按照硬件设计活动组织CWE条目
	CWEViewHardwareDesign = 1199

	// CWEViewCWECrossSection CWE横截面视图 (CWE-888)
	// 提供CWE条目的横截面视图
	CWEViewCWECrossSection = 888

	// CWEViewComprehensiveDictionary 综合CWE字典 (CWE-1400)
	// 包含所有CWE条目的综合视图
	CWEViewComprehensiveDictionary = 1400
)

知名视图ID常量

View Source
const DefaultBaseURL = "https://cwe-api.mitre.org/api/v1"

DefaultBaseURL 是MITRE CWE REST API的默认基础URL

View Source
const DefaultTimeout = 30 * time.Second

DefaultTimeout 是HTTP请求的默认超时时间

View Source
const DefaultUserAgent = "cwe-sdk-go/" + Version

DefaultUserAgent 是HTTP请求的默认User-Agent

View Source
const Version = "v0.0.1"

Version 表示本SDK的版本号

Variables

View Source
var CWETop25 = []int{
	79,
	89,
	352,
	862,
	787,
	22,
	416,
	125,
	78,
	94,
	120,
	434,
	476,
	121,
	502,
	122,
	863,
	20,
	284,
	200,
	306,
	918,
	77,
	639,
	770,
}

CWETop25 包含CWE Top 25最危险软件弱点列表(2024版)。

该列表由MITRE基于NVD数据的频率分析和CVSS评分计算得出, 代表了对软件最严重的安全威胁。

使用场景:

  • 安全工具优先级排序
  • 开发者安全培训重点
  • 漏洞管理风险评估
View Source
var OWASPTop10 = map[string][]int{
	"A01:2021-Broken Access Control": {
		22, 23, 35, 59, 78, 94, 200, 201, 219, 255, 269, 276,
		284, 285, 287, 306, 346, 639, 651, 668, 862, 863, 922,
	},
	"A02:2021-Cryptographic Failures": {
		260, 261, 295, 310, 311, 312, 319, 325, 326, 327, 328,
		329, 330, 337, 338, 340, 347, 522, 757, 759, 760, 780,
	},
	"A03:2021-Injection": {
		20, 74, 75, 77, 78, 79, 80, 83, 87, 88, 89, 90, 91,
		94, 95, 96, 97, 98, 99, 100, 113, 116, 138, 141, 147,
		150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160,
		161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171,
	},
	"A04:2021-Insecure Design": {
		209, 235, 256, 267, 284, 285, 287, 311, 326, 384, 393, 664, 863,
	},
	"A05:2021-Security Misconfiguration": {
		2, 5, 11, 13, 15, 16, 260, 315, 520, 526, 537, 540, 544, 546,
		547, 548, 611, 613, 614, 759, 760, 1021,
	},
	"A06:2021-Vulnerable and Outdated Components": {},
	"A07:2021-Identification and Authentication Failures": {
		255, 256, 258, 259, 260, 287, 288, 290, 294, 295, 297,
		306, 307, 346, 384, 521, 522, 523, 613, 620, 640, 798,
	},
	"A08:2021-Software and Data Integrity Failures": {
		311, 345, 353, 426, 494, 502, 565, 610, 653, 754, 829, 912,
	},
	"A09:2021-Security Logging and Monitoring Failures": {
		117, 223, 532, 778,
	},
	"A10:2021-Server-Side Request Forgery (SSRF)": {
		918, 1021,
	},
}

OWASPTop10 包含OWASP Top 10(2021版)到CWE ID的映射。

OWASP Top 10是Web应用安全风险的行业标准列表, 每个类别映射到相关的CWE ID。

使用场景:

  • Web应用安全评估
  • 合规性检查
  • 安全测试用例设计
View Source
var SANSTop25 = []int{
	89,
	78,
	79,
	20,
	22,
	352,
	416,
	787,
	125,
	94,
	190,
	434,
	862,
	287,
	306,
	863,
	798,
	502,
	77,
	119,
	639,
	770,
	918,
	476,
	200,
}

SANSTop25 包含SANS Top 25最危险软件错误列表。

SANS Top 25由SANS Institute与MITRE合作编制, 侧重于可被攻击者利用来获取系统控制权的编程错误。

Functions

func CompareCWEIDs

func CompareCWEIDs(a, b string) (int, error)

CompareCWEIDs 比较两个CWE ID的数值大小。

参数:

  • a: 第一个CWE ID字符串
  • b: 第二个CWE ID字符串

返回值:

  • int: 如果a < b返回-1,a == b返回0,a > b返回1
  • error: 如果任一CWE ID格式无效,返回错误

示例:

CompareCWEIDs("CWE-79", "CWE-89")   // 返回 -1, nil
CompareCWEIDs("CWE-79", "CWE-79")   // 返回 0, nil
CompareCWEIDs("CWE-89", "CWE-79")   // 返回 1, nil

func CountByAbstraction

func CountByAbstraction(r *Registry, a Abstraction) int

CountByAbstraction 统计指定抽象层级的CWE条目数量。

func CountByLikelihood

func CountByLikelihood(r *Registry, l LikelihoodOfExploit) int

CountByLikelihood 统计指定利用可能性的CWE条目数量。

func CountByScope

func CountByScope(r *Registry, scope ConsequenceScope) int

CountByScope 统计具有指定后果范围的CWE条目数量。

func CountByStatus

func CountByStatus(r *Registry, s Status) int

CountByStatus 统计指定状态的CWE条目数量。

func ExtractCWEIDs

func ExtractCWEIDs(text string) []string

ExtractCWEIDs 从文本中提取所有CWE ID。

该函数在给定的文本中搜索所有匹配CWE ID格式的子串, 返回所有找到的标准格式CWE ID列表。

参数:

  • text: 需要搜索的文本

返回值:

  • []string: 找到的所有CWE ID列表,格式为 "CWE-NNN"。如果没有找到,返回空切片。

示例:

ExtractCWEIDs("See CWE-79 and CWE-89 for details")
// 返回 ["CWE-79", "CWE-89"]

ExtractCWEIDs("No CWE IDs here")
// 返回 []

func ExtractFirstCWEID

func ExtractFirstCWEID(text string) string

ExtractFirstCWEID 从文本中提取第一个CWE ID。

参数:

  • text: 需要搜索的文本

返回值:

  • string: 找到的第一个CWE ID,格式为 "CWE-NNN"。如果没有找到,返回空字符串。

示例:

ExtractFirstCWEID("See CWE-79 and CWE-89")
// 返回 "CWE-79"

ExtractFirstCWEID("No CWE IDs here")
// 返回 ""

func FormatCWEID

func FormatCWEID(id string) (string, error)

FormatCWEID 将CWE ID格式化为标准格式 "CWE-NNN"。

该函数接受各种常见的CWE ID格式,统一输出为大写的 "CWE-NNN" 格式。 输入可以是纯数字、"CWE-79"、"cwe-79"、"CWE79" 等格式。

参数:

  • id: 需要格式化的CWE ID字符串

返回值:

  • string: 格式化后的标准CWE ID字符串,如 "CWE-79"
  • error: 如果输入不是有效的CWE ID格式,返回InvalidCWEIDError

示例:

FormatCWEID("79")     // 返回 "CWE-79", nil
FormatCWEID("cwe-79") // 返回 "CWE-79", nil
FormatCWEID("CWE79")  // 返回 "CWE-79", nil
FormatCWEID("")       // 返回 "", InvalidCWEIDError

func FormatCWEIDFromInt

func FormatCWEIDFromInt(id int) string

FormatCWEIDFromInt 将整数ID格式化为标准CWE ID字符串 "CWE-NNN"。

参数:

  • id: 整数形式的CWE ID

返回值:

  • string: 格式化后的标准CWE ID字符串

示例:

FormatCWEIDFromInt(79)  // 返回 "CWE-79"
FormatCWEIDFromInt(1000) // 返回 "CWE-1000"

func GetOWASPCategories

func GetOWASPCategories(cweID int) []string

GetOWASPCategories 获取给定CWE ID所属的所有OWASP Top 10类别。

与GetOWASPCategory不同,该函数返回所有匹配的类别。

参数:

  • cweID: 需要查询的CWE ID数字

返回值:

  • []string: 所有匹配的OWASP类别名称列表,如果没有匹配返回空切片

func GetOWASPCategory

func GetOWASPCategory(cweID int) string

GetOWASPCategory 获取给定CWE ID所属的OWASP Top 10类别。

如果CWE ID属于多个类别,只返回第一个匹配的类别。

参数:

  • cweID: 需要查询的CWE ID数字

返回值:

  • string: OWASP类别名称(如 "A01:2021-Broken Access Control"),如果不在任何类别中返回空字符串

func GroupByAbstraction

func GroupByAbstraction(cwes []*CWE) map[Abstraction][]*CWE

GroupByAbstraction 按抽象层级分组。

func GroupByLikelihood

func GroupByLikelihood(cwes []*CWE) map[LikelihoodOfExploit][]*CWE

GroupByLikelihood 按利用可能性分组。

func GroupByStatus

func GroupByStatus(cwes []*CWE) map[Status][]*CWE

GroupByStatus 按状态分组。

func IsCWEID

func IsCWEID(text string) bool

IsCWEID 检查给定的字符串是否为有效的CWE ID格式。

该函数仅检查格式是否正确,不验证该CWE ID是否实际存在于MITRE数据库中。

参数:

  • text: 需要检查的字符串

返回值:

  • bool: 如果是有效的CWE ID格式返回true,否则返回false

示例:

IsCWEID("CWE-79")  // 返回 true
IsCWEID("79")      // 返回 true
IsCWEID("abc")     // 返回 false
IsCWEID("")        // 返回 false

func IsInOWASPTop10

func IsInOWASPTop10(cweID int) bool

IsInOWASPTop10 检查给定的CWE ID是否在OWASP Top 10映射中。

参数:

  • cweID: 需要检查的CWE ID数字

返回值:

  • bool: 如果在OWASP Top 10中返回true,否则返回false

func IsInSANSTop25

func IsInSANSTop25(cweID int) bool

IsInSANSTop25 检查给定的CWE ID是否在SANS Top 25列表中。

参数:

  • cweID: 需要检查的CWE ID数字

返回值:

  • bool: 如果在SANS Top 25中返回true,否则返回false

func IsInTop25

func IsInTop25(cweID int) bool

IsInTop25 检查给定的CWE ID是否在CWE Top 25列表中。

参数:

  • cweID: 需要检查的CWE ID数字

返回值:

  • bool: 如果在Top 25中返回true,否则返回false

func IsInWellKnownView

func IsInWellKnownView(viewID int) bool

IsInWellKnownView 检查给定的视图ID是否为知名视图。

知名视图包括:CWE-1000(研究概念)、CWE-699(软件开发)、 CWE-1199(硬件设计)、CWE-888(横截面)、CWE-1400(综合字典)。

参数:

  • viewID: 需要检查的视图ID数字

返回值:

  • bool: 如果是知名视图返回true,否则返回false

func MarshalCSV

func MarshalCSV(cwes []*CWE) ([]byte, error)

MarshalCSV 将CWE条目列表序列化为CSV格式。

func MarshalJSON

func MarshalJSON(cwe *CWE) ([]byte, error)

MarshalJSON 将CWE条目序列化为JSON格式。

参数:

  • cwe: 要序列化的CWE条目

返回值:

  • []byte: JSON数据
  • error: 序列化失败时返回错误

func MarshalJSONList

func MarshalJSONList(cwes []*CWE) ([]byte, error)

MarshalJSONList 将CWE条目列表序列化为JSON格式。

func MarshalXML

func MarshalXML(cwe *CWE) ([]byte, error)

MarshalXML 将CWE条目序列化为XML格式。

func ParseCWEID

func ParseCWEID(id string) (int, error)

ParseCWEID 从CWE ID字符串中提取数字部分。

支持的输入格式:

  • 纯数字: "79", "079"
  • 标准格式: "CWE-79", "CWE-079"
  • 无连字符: "CWE79"
  • 大小写不敏感: "cwe-79", "Cwe-79"

参数:

  • id: 需要解析的CWE ID字符串

返回值:

  • int: 提取出的数字ID
  • error: 如果输入不是有效的CWE ID格式,返回InvalidCWEIDError

示例:

ParseCWEID("CWE-79")  // 返回 79, nil
ParseCWEID("79")      // 返回 79, nil
ParseCWEID("cwe-079") // 返回 79, nil
ParseCWEID("")        // 返回 0, InvalidCWEIDError
ParseCWEID("abc")     // 返回 0, InvalidCWEIDError

func ValidateCWEID

func ValidateCWEID(text string) error

ValidateCWEID 验证CWE ID格式并返回详细的错误信息。

该函数对CWE ID进行完整验证,包括格式检查和基本的有效性检查。 与IsCWEID不同,该函数返回详细的错误信息,方便调用方进行错误处理。

参数:

  • text: 需要验证的CWE ID字符串

返回值:

  • error: 如果验证通过返回nil,否则返回InvalidCWEIDError

示例:

err := ValidateCWEID("CWE-79")  // 返回 nil
err := ValidateCWEID("")        // 返回 InvalidCWEIDError

Types

type APIClient

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

APIClient 是MITRE CWE REST API的客户端。

该客户端封装了HTTP请求逻辑,提供了对CWE REST API的完整访问能力。 支持自定义基础URL、超时时间、速率限制等配置。

示例:

client := cwe.NewAPIClient()
weakness, err := client.GetWeakness(context.Background(), 79)

// 自定义配置
client := cwe.NewAPIClient(
    cwe.WithAPITimeout(60*time.Second),
    cwe.WithAPIRateLimit(0.5, 1),
)

func NewAPIClient

func NewAPIClient(opts ...APIClientOption) *APIClient

NewAPIClient 创建一个新的APIClient实例。

默认使用MITRE CWE REST API的基础URL和30秒超时。

参数:

  • opts: 可选的配置选项

返回值:

  • *APIClient: 新创建的APIClient实例

func (*APIClient) Close

func (c *APIClient) Close()

Close 关闭API客户端,释放资源。

func (*APIClient) GetAncestors

func (c *APIClient) GetAncestors(ctx context.Context, id int) ([]Relationship, error)

GetAncestors 获取指定CWE条目的所有祖先关系。

该方法调用 MITRE CWE REST API 的 GET /cwe/{id}/ancestors 端点, 返回此CWE条目的所有祖先(递归的父级)关系。

参数:

  • ctx: 请求上下文
  • id: CWE ID数字

返回值:

  • []Relationship: 祖先关系列表
  • error: 请求失败时返回错误

func (*APIClient) GetBaseURL

func (c *APIClient) GetBaseURL() string

GetBaseURL 获取API的基础URL。

func (*APIClient) GetCWEs

func (c *APIClient) GetCWEs(ctx context.Context, ids []int) (map[string]*CWE, error)

GetCWEs 批量获取多个CWE弱点。

该方法调用 MITRE CWE REST API 的 GET /cwe/{ids} 端点, 可以一次获取多个CWE弱点的信息。

参数:

  • ctx: 请求上下文
  • ids: CWE ID数字列表

返回值:

  • map[string]*CWE: 以CWE ID字符串为键的弱点映射
  • error: 请求失败时返回错误

func (*APIClient) GetCategory

func (c *APIClient) GetCategory(ctx context.Context, id int) (*Category, error)

GetCategory 获取指定ID的CWE类别详情。

该方法调用 MITRE CWE REST API 的 GET /cwe/category/{id} 端点。

参数:

  • ctx: 请求上下文
  • id: 类别ID数字

返回值:

  • *Category: 类别详情
  • error: 请求失败时返回错误

func (*APIClient) GetChildren

func (c *APIClient) GetChildren(ctx context.Context, id int, viewID ...int) ([]Relationship, error)

GetChildren 获取指定CWE条目的子级关系。

该方法调用 MITRE CWE REST API 的 GET /cwe/{id}/children 端点, 返回在指定视图中此CWE条目的所有子级关系。

参数:

  • ctx: 请求上下文
  • id: CWE ID数字
  • viewID: 可选的视图ID,用于限定关系范围

返回值:

  • []Relationship: 子级关系列表
  • error: 请求失败时返回错误

func (*APIClient) GetDescendants

func (c *APIClient) GetDescendants(ctx context.Context, id int) ([]Relationship, error)

GetDescendants 获取指定CWE条目的所有后代关系。

该方法调用 MITRE CWE REST API 的 GET /cwe/{id}/descendants 端点, 返回此CWE条目的所有后代(递归的子级)关系。

参数:

  • ctx: 请求上下文
  • id: CWE ID数字

返回值:

  • []Relationship: 后代关系列表
  • error: 请求失败时返回错误

func (*APIClient) GetHTTPClient

func (c *APIClient) GetHTTPClient() *HTTPClient

GetHTTPClient 获取底层的HTTPClient实例。

func (*APIClient) GetParents

func (c *APIClient) GetParents(ctx context.Context, id int, viewID ...int) ([]Relationship, error)

GetParents 获取指定CWE条目的父级关系。

该方法调用 MITRE CWE REST API 的 GET /cwe/{id}/parents 端点, 返回在指定视图中此CWE条目的所有父级关系。

参数:

  • ctx: 请求上下文
  • id: CWE ID数字
  • viewID: 可选的视图ID,用于限定关系范围

返回值:

  • []Relationship: 父级关系列表
  • error: 请求失败时返回错误

func (*APIClient) GetRateLimiter

func (c *APIClient) GetRateLimiter() *RateLimiter

GetRateLimiter 获取速率限制器。

func (*APIClient) GetVersion

func (c *APIClient) GetVersion(ctx context.Context) (*VersionResponse, error)

GetVersion 获取当前CWE数据的版本信息。

该方法调用 MITRE CWE REST API 的 GET /version 端点, 返回当前CWE数据库的版本号和发布日期。

参数:

  • ctx: 请求上下文

返回值:

  • *VersionResponse: 版本信息
  • error: 请求失败时返回错误

示例:

client := cwe.NewAPIClient()
version, err := client.GetVersion(context.Background())
if err != nil {
    log.Fatal(err)
}
fmt.Printf("CWE Version: %s, Release Date: %s\n", version.Version, version.ReleaseDate)

func (*APIClient) GetView

func (c *APIClient) GetView(ctx context.Context, id int) (*View, error)

GetView 获取指定ID的CWE视图详情。

该方法调用 MITRE CWE REST API 的 GET /cwe/view/{id} 端点。

参数:

  • ctx: 请求上下文
  • id: 视图ID数字,例如 1000

返回值:

  • *View: 视图详情
  • error: 请求失败时返回错误

func (*APIClient) GetWeakness

func (c *APIClient) GetWeakness(ctx context.Context, id int) (*CWE, error)

GetWeakness 获取指定ID的CWE弱点详情。

该方法调用 MITRE CWE REST API 的 GET /cwe/weakness/{id} 端点, 返回包含完整信息的弱点数据。

参数:

  • ctx: 请求上下文,用于超时和取消控制
  • id: CWE ID数字,例如 79

返回值:

  • *CWE: 弱点详情
  • error: 请求失败或解析失败时返回错误

示例:

client := cwe.NewAPIClient()
weakness, err := client.GetWeakness(context.Background(), 79)
if err != nil {
    log.Fatal(err)
}
fmt.Println(weakness.Name) // 输出: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')

func (*APIClient) SetBaseURL

func (c *APIClient) SetBaseURL(url string)

SetBaseURL 设置API的基础URL。

func (*APIClient) SetHTTPClient

func (c *APIClient) SetHTTPClient(client *HTTPClient)

SetHTTPClient 设置底层的HTTPClient实例。

func (*APIClient) SetRateLimiter

func (c *APIClient) SetRateLimiter(limiter *RateLimiter)

SetRateLimiter 设置速率限制器。

type APIClientOption

type APIClientOption func(*APIClient)

APIClientOption 是APIClient的配置选项函数类型

func WithAPIBaseURL

func WithAPIBaseURL(url string) APIClientOption

WithAPIBaseURL 设置API的基础URL。

参数:

func WithAPIHTTPClient

func WithAPIHTTPClient(opts ...HTTPClientOption) APIClientOption

WithAPIHTTPClient 设置自定义的HTTP客户端选项。

参数:

  • opts: HTTPClient的配置选项

func WithAPIRateLimit

func WithAPIRateLimit(rate float64, burst int) APIClientOption

WithAPIRateLimit 设置API请求的速率限制。

参数:

  • rate: 每秒允许的请求数
  • burst: 允许的突发请求数

func WithAPIRetry

func WithAPIRetry(maxRetries int, delay time.Duration) APIClientOption

WithAPIRetry 设置API请求的重试策略。

参数:

  • maxRetries: 最大重试次数
  • delay: 重试间隔

func WithAPITimeout

func WithAPITimeout(timeout time.Duration) APIClientOption

WithAPITimeout 设置API请求的超时时间。

参数:

  • timeout: 超时时间

type APIError

type APIError struct {
	*CWEError
	// StatusCode HTTP状态码
	StatusCode int
	// URL 请求的URL
	URL string
	// Method HTTP方法
	Method string
}

APIError 表示CWE API调用失败的错误。

当对MITRE CWE REST API的请求返回错误状态码时返回此错误。

func NewAPIError

func NewAPIError(statusCode int, url, method string) *APIError

NewAPIError 创建一个新的APIError。

参数:

  • statusCode: HTTP状态码
  • url: 请求的URL
  • method: HTTP方法

type APIResponse

type APIResponse struct {
	// Data 包含API返回的数据
	Data json.RawMessage `json:"Data"`
	// Message 可选的消息字段
	Message string `json:"Message,omitempty"`
}

APIResponse 是MITRE CWE REST API的基础响应结构。

所有API响应都包含Data字段和可选的Message字段。

type Abstraction

type Abstraction string

Abstraction 表示CWE条目的抽象层级。

CWE按照抽象程度从高到低分为四个层级: Pillar(柱石)> Class(类)> Base(基础)> Variant(变体)。 抽象层级越高,描述越通用;层级越低,描述越具体。

其中 Base 级别是映射到漏洞根因的首选级别。

const (
	// AbstractionPillar 表示柱石级别,最高抽象层级,代表一个主题
	// 例如:CWE-664 不正确的资源生命周期控制
	AbstractionPillar Abstraction = "Pillar"

	// AbstractionClass 表示类级别,通常与特定语言或技术无关
	// 例如:CWE-74 输出中特殊元素的不当中和(注入)
	AbstractionClass Abstraction = "Class"

	// AbstractionBase 表示基础级别,足够具体以推断检测/预防方法
	// 例如:CWE-79 XSS, CWE-89 SQL注入
	// 这是映射到漏洞根因的首选级别
	AbstractionBase Abstraction = "Base"

	// AbstractionVariant 表示变体级别,特定于某资源、技术或上下文
	// 例如:CWE-83 网页属性中脚本的不当中和
	AbstractionVariant Abstraction = "Variant"
)

func AllAbstractionValues

func AllAbstractionValues() []Abstraction

AllAbstractionValues 返回所有有效的抽象层级值。

func ParseAbstraction

func ParseAbstraction(s string) (Abstraction, error)

ParseAbstraction 从字符串解析抽象层级。

参数:

  • s: 需要解析的字符串

返回值:

  • Abstraction: 解析出的抽象层级
  • error: 如果字符串不是有效的抽象层级,返回错误

func (Abstraction) AbstractionOrder

func (a Abstraction) AbstractionOrder() int

AbstractionOrder 返回抽象层级的排序权重,层级越高值越大。 Pillar=4, Class=3, Base=2, Variant=1, 未知=0

func (Abstraction) IsValid

func (a Abstraction) IsValid() bool

IsValid 检查抽象层级是否为有效值。

func (Abstraction) String

func (a Abstraction) String() string

String 返回抽象层级的字符串表示。

type AlternateTerm

type AlternateTerm struct {
	// Term 备用术语名称
	Term string `json:"term" xml:"Term"`
	// Description 备用术语的描述
	Description string `json:"description,omitempty" xml:"Description,omitempty"`
}

AlternateTerm 表示备用术语。

备用术语提供了该CWE条目的其他常用名称或术语。

type ApplicablePlatforms

type ApplicablePlatforms struct {
	// Languages 适用的编程语言列表
	Languages []PlatformEntry `json:"languages,omitempty" xml:"Languages>Language,omitempty"`
	// OperatingSystems 适用的操作系统列表
	OperatingSystems []PlatformEntry `json:"operating_systems,omitempty" xml:"Operating_Systems>Operating_System,omitempty"`
	// Architectures 适用的架构列表
	Architectures []PlatformEntry `json:"architectures,omitempty" xml:"Architectures>Architecture,omitempty"`
	// Technologies 适用的技术列表
	Technologies []PlatformEntry `json:"technologies,omitempty" xml:"Technologies>Technology,omitempty"`
}

ApplicablePlatforms 表示CWE条目适用的平台信息。

适用平台包括编程语言、操作系统、架构和技术等方面。

type BasicFetcher

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

BasicFetcher 通过API获取单个CWE条目的获取器。

示例:

client := cwe.NewAPIClient()
fetcher := cwe.NewBasicFetcher(client)
cwe79, err := fetcher.Fetch(context.Background(), 79)

func NewBasicFetcher

func NewBasicFetcher(client *APIClient) *BasicFetcher

NewBasicFetcher 创建一个新的基础获取器。

参数:

  • client: API客户端实例

func (*BasicFetcher) Fetch

func (f *BasicFetcher) Fetch(ctx context.Context, id int) (*CWE, error)

Fetch 通过API获取指定ID的CWE弱点条目。

func (*BasicFetcher) FetchCategory

func (f *BasicFetcher) FetchCategory(ctx context.Context, id int) (*Category, error)

FetchCategory 通过API获取指定ID的CWE类别。

func (*BasicFetcher) FetchView

func (f *BasicFetcher) FetchView(ctx context.Context, id int) (*View, error)

FetchView 通过API获取指定ID的CWE视图。

func (*BasicFetcher) FetchWithRelations

func (f *BasicFetcher) FetchWithRelations(ctx context.Context, id int, viewID ...int) (*CWE, error)

FetchWithRelations 通过API获取指定ID的CWE条目及其关系。

该方法不仅获取CWE条目本身,还获取其父级和子级关系信息, 并将关系信息填充到CWE条目的Relationships字段中。

type CWE

type CWE struct {
	// ID CWE条目的数字标识符
	ID int `json:"id" xml:"ID,attr"`
	// Name CWE条目的名称
	Name string `json:"name" xml:"Name"`
	// Abstraction 抽象层级(Pillar、Class、Base、Variant)
	Abstraction Abstraction `json:"abstraction,omitempty" xml:"Abstraction,omitempty"`
	// Structure 结构类型(Simple、Chain、Composite)
	Structure Structure `json:"structure,omitempty" xml:"Structure,omitempty"`
	// Status 状态(Stable、Usable、Draft、Incomplete、Obsolete、Deprecated)
	Status Status `json:"status,omitempty" xml:"Status,omitempty"`
	// Description 弱点描述
	Description string `json:"description" xml:"Description"`
	// ExtendedDescription 扩展描述,提供更详细的说明
	ExtendedDescription string `json:"extended_description,omitempty" xml:"Extended_Description,omitempty"`
	// LikelihoodOfExploit 被利用的可能性
	LikelihoodOfExploit LikelihoodOfExploit `json:"likelihood_of_exploit,omitempty" xml:"LikelihoodOfExploit,omitempty"`
	// CommonConsequences 常见后果列表
	CommonConsequences []Consequence `json:"common_consequences,omitempty" xml:"CommonConsequences>Consequence,omitempty"`
	// PotentialMitigations 潜在缓解措施列表
	PotentialMitigations []Mitigation `json:"potential_mitigations,omitempty" xml:"PotentialMitigations>Mitigation,omitempty"`
	// DemonstrativeExamples 示范性示例列表
	DemonstrativeExamples []DemonstrativeExample `json:"demonstrative_examples,omitempty" xml:"DemonstrativeExamples>DemonstrativeExample,omitempty"`
	// ObservedExamples 观察到的示例列表
	ObservedExamples []ObservedExample `json:"observed_examples,omitempty" xml:"ObservedExamples>ObservedExample,omitempty"`
	// References 参考文献列表
	References []Reference `json:"references,omitempty" xml:"References>Reference,omitempty"`
	// Relationships 关系列表
	Relationships []Relationship `json:"relationships,omitempty" xml:"Relationships>Relationship,omitempty"`
	// ApplicablePlatforms 适用平台信息
	ApplicablePlatforms *ApplicablePlatforms `json:"applicable_platforms,omitempty" xml:"ApplicablePlatforms,omitempty"`
	// ModesOfIntroduction 引入方式列表
	ModesOfIntroduction []Introduction `json:"modes_of_introduction,omitempty" xml:"ModesOfIntroduction>Introduction,omitempty"`
	// AlternateTerms 备用术语列表
	AlternateTerms []AlternateTerm `json:"alternate_terms,omitempty" xml:"AlternateTerms>AlternateTerm,omitempty"`
	// Notes 备注信息
	Notes string `json:"notes,omitempty" xml:"Notes,omitempty"`
	// ContentHistory 内容历史
	ContentHistory *ContentHistory `json:"content_history,omitempty" xml:"ContentHistory,omitempty"`
	// CWEType CWE条目类型(weakness、category、view、compound_element)
	CWEType string `json:"cwe_type" xml:"-"`
	// URL CWE条目的URL地址
	URL string `json:"url,omitempty" xml:"-"`
}

CWE 表示一个CWE弱点条目,是SDK的核心类型。

CWE(Common Weakness Enumeration,通用弱点枚举)条目描述了一种特定的安全弱点, 包括其描述、抽象层级、结构类型、后果、缓解措施等信息。

func Deduplicate

func Deduplicate(cwes []*CWE) []*CWE

Deduplicate 对CWE条目列表去重(按ID)。

func Filter

func Filter(cwes []*CWE, opts ...FilterOption) []*CWE

Filter 根据过滤选项过滤CWE条目列表。

所有非零值的选项都会作为过滤条件,条件之间是AND关系。 零值的选项被忽略。

参数:

  • cwes: 要过滤的CWE条目列表
  • opts: 过滤选项(可以指定多个,但只使用第一个)

返回值:

  • []*CWE: 过滤后的CWE条目列表

func FindBaseWeaknesses

func FindBaseWeaknesses(r *Registry) []*CWE

FindBaseWeaknesses 查找所有基础级别的CWE弱点。

参数:

  • r: CWE注册表

返回值:

  • []*CWE: 所有基础级别CWE条目

func FindByAbstraction

func FindByAbstraction(r *Registry, abstraction Abstraction) []*CWE

FindByAbstraction 在注册表中查找指定抽象层级的所有CWE条目。

参数:

  • r: CWE注册表
  • abstraction: 抽象层级

返回值:

  • []*CWE: 匹配的CWE条目列表

func FindByConsequenceScope

func FindByConsequenceScope(r *Registry, scope ConsequenceScope) []*CWE

FindByConsequenceScope 在注册表中查找具有指定后果范围的所有CWE条目。

参数:

  • r: CWE注册表
  • scope: 后果范围

返回值:

  • []*CWE: 匹配的CWE条目列表

func FindByID

func FindByID(r *Registry, id int) (*CWE, bool)

FindByID 在注册表中根据ID查找CWE弱点条目。

参数:

  • r: CWE注册表
  • id: 要查找的CWE ID

返回值:

  • *CWE: 找到的CWE条目,如果未找到返回nil
  • bool: 是否找到

func FindByKeyword

func FindByKeyword(r *Registry, keyword string) []*CWE

FindByKeyword 在注册表中根据关键字搜索CWE条目。

搜索范围包括名称和描述字段,匹配是不区分大小写的。

参数:

  • r: CWE注册表
  • keyword: 搜索关键字

返回值:

  • []*CWE: 匹配的CWE条目列表

func FindByLikelihood

func FindByLikelihood(r *Registry, likelihood LikelihoodOfExploit) []*CWE

FindByLikelihood 在注册表中查找指定利用可能性的所有CWE条目。

参数:

  • r: CWE注册表
  • likelihood: 利用可能性

返回值:

  • []*CWE: 匹配的CWE条目列表

func FindByStatus

func FindByStatus(r *Registry, status Status) []*CWE

FindByStatus 在注册表中查找指定状态的所有CWE条目。

参数:

  • r: CWE注册表
  • status: CWE状态

返回值:

  • []*CWE: 匹配的CWE条目列表

func FindByStructure

func FindByStructure(r *Registry, structure Structure) []*CWE

FindByStructure 在注册表中查找指定结构类型的所有CWE条目。

参数:

  • r: CWE注册表
  • structure: 结构类型

返回值:

  • []*CWE: 匹配的CWE条目列表

func FindChains

func FindChains(r *Registry) []*CWE

FindChains 查找所有链式CWE条目。

参数:

  • r: CWE注册表

返回值:

  • []*CWE: 所有链式CWE条目

func FindComposites

func FindComposites(r *Registry) []*CWE

FindComposites 查找所有复合CWE条目。

参数:

  • r: CWE注册表

返回值:

  • []*CWE: 所有复合CWE条目

func FindTopLevel

func FindTopLevel(r *Registry) []*CWE

FindTopLevel 查找所有顶层(Pillar抽象级别)的CWE条目。

参数:

  • r: CWE注册表

返回值:

  • []*CWE: 所有顶层CWE条目

func NewCWE

func NewCWE(id int, name string) *CWE

NewCWE 创建一个新的CWE弱点条目。

创建的CWE条目默认CWEType为"weakness"。

参数:

  • id: CWE条目的数字标识符
  • name: CWE条目的名称

返回值:

  • *CWE: 新创建的CWE实例

func SortByAbstraction

func SortByAbstraction(cwes []*CWE) []*CWE

SortByAbstraction 按抽象层级从高到低排序。

func SortByID

func SortByID(cwes []*CWE) []*CWE

SortByID 按CWE ID升序排序。

func SortByName

func SortByName(cwes []*CWE) []*CWE

SortByName 按CWE名称升序排序。

func UnmarshalCSV

func UnmarshalCSV(data []byte) ([]*CWE, error)

UnmarshalCSV 从CSV数据反序列化CWE条目列表。

func UnmarshalJSON

func UnmarshalJSON(data []byte) (*CWE, error)

UnmarshalJSON 从JSON数据反序列化CWE条目。

参数:

  • data: JSON数据

返回值:

  • *CWE: 反序列化的CWE条目
  • error: 反序列化失败时返回错误

func UnmarshalJSONList

func UnmarshalJSONList(data []byte) ([]*CWE, error)

UnmarshalJSONList 从JSON数据反序列化CWE条目列表。

func UnmarshalXML

func UnmarshalXML(data []byte) (*CWE, error)

UnmarshalXML 从XML数据反序列化CWE条目。

func (*CWE) CWEID

func (c *CWE) CWEID() string

CWEID 返回标准格式的CWE ID字符串。

返回值:

  • string: 格式为"CWE-NNN"的标准CWE ID

func (*CWE) GetChainIDs

func (c *CWE) GetChainIDs() []int

GetChainIDs 获取与此弱点相关的链式CWE ID。

通过遍历Relationships中Nature为CanPrecede或CanFollow的关系来获取链式ID。

返回值:

  • []int: 链式CWE ID列表

func (*CWE) GetChildIDs

func (c *CWE) GetChildIDs() []int

GetChildIDs 获取此弱点的所有子级CWE ID。

通过遍历Relationships中Nature为ParentOf的关系来获取子级ID。

返回值:

  • []int: 子级CWE ID列表

func (*CWE) GetParentIDs

func (c *CWE) GetParentIDs() []int

GetParentIDs 获取此弱点的所有父级CWE ID。

通过遍历Relationships中Nature为ChildOf的关系来获取父级ID。

返回值:

  • []int: 父级CWE ID列表

func (*CWE) GetPeerIDs

func (c *CWE) GetPeerIDs() []int

GetPeerIDs 获取此弱点的所有对等CWE ID。

通过遍历Relationships中Nature为PeerOf或CanAlsoBe的关系来获取对等ID。

返回值:

  • []int: 对等CWE ID列表

func (*CWE) HasConsequenceScope

func (c *CWE) HasConsequenceScope(scope ConsequenceScope) bool

HasConsequenceScope 检查CWE条目是否包含指定的后果范围。

遍历所有CommonConsequences,检查是否有任何后果包含指定的安全范围。

参数:

  • scope: 需要检查的安全范围

返回值:

  • bool: 如果任何后果包含该安全范围返回true,否则返回false

func (*CWE) IsBase

func (c *CWE) IsBase() bool

IsBase 检查CWE条目是否为基础级别。

返回值:

  • bool: 如果Abstraction为AbstractionBase返回true,否则返回false

func (*CWE) IsCategory

func (c *CWE) IsCategory() bool

IsCategory 检查CWE条目是否为类别类型。

返回值:

  • bool: 如果CWEType为"category"返回true,否则返回false

func (*CWE) IsChain

func (c *CWE) IsChain() bool

IsChain 检查CWE条目是否为链式结构。

返回值:

  • bool: 如果Structure为StructureChain返回true,否则返回false

func (*CWE) IsComposite

func (c *CWE) IsComposite() bool

IsComposite 检查CWE条目是否为复合结构。

返回值:

  • bool: 如果Structure为StructureComposite返回true,否则返回false

func (*CWE) IsCompoundElement

func (c *CWE) IsCompoundElement() bool

IsCompoundElement 检查CWE条目是否为复合元素类型。

返回值:

  • bool: 如果CWEType为"compound_element"返回true,否则返回false

func (*CWE) IsDeprecated

func (c *CWE) IsDeprecated() bool

IsDeprecated 检查CWE条目是否已废弃。

返回值:

  • bool: 如果Status为StatusDeprecated返回true,否则返回false

func (*CWE) IsPillar

func (c *CWE) IsPillar() bool

IsPillar 检查CWE条目是否为柱石级别。

返回值:

  • bool: 如果Abstraction为AbstractionPillar返回true,否则返回false

func (*CWE) IsStable

func (c *CWE) IsStable() bool

IsStable 检查CWE条目是否为稳定状态。

返回值:

  • bool: 如果Status为StatusStable返回true,否则返回false

func (*CWE) IsVariant

func (c *CWE) IsVariant() bool

IsVariant 检查CWE条目是否为变体级别。

返回值:

  • bool: 如果Abstraction为AbstractionVariant返回true,否则返回false

func (*CWE) IsView

func (c *CWE) IsView() bool

IsView 检查CWE条目是否为视图类型。

返回值:

  • bool: 如果CWEType为"view"返回true,否则返回false

func (*CWE) IsWeakness

func (c *CWE) IsWeakness() bool

IsWeakness 检查CWE条目是否为弱点类型。

返回值:

  • bool: 如果CWEType为"weakness"返回true,否则返回false

func (*CWE) Validate

func (c *CWE) Validate() error

Validate 验证CWE条目的有效性。

检查条件:

  • ID必须大于0
  • Name不能为空

返回值:

  • error: 如果验证失败返回ValidationError,否则返回nil

type CWEError

type CWEError struct {
	// Code 错误码
	Code string
	// Message 错误消息
	Message string
	// Detail 详细信息
	Detail string
	// Err 被包装的内部错误
	Err error
}

CWEError 是所有CWE SDK错误的基础类型。

该类型提供了统一的错误结构,包含错误码、消息和详细信息, 方便上层应用进行错误分类和处理。

func (*CWEError) Error

func (e *CWEError) Error() string

Error 实现error接口,返回格式化的错误消息。

func (*CWEError) Unwrap

func (e *CWEError) Unwrap() error

Unwrap 返回被包装的内部错误,支持errors.Is/As链式查找。

type CWENotFoundError

type CWENotFoundError struct {
	*CWEError
	// ID 未找到的CWE ID
	ID int
}

CWENotFoundError 表示CWE条目未找到的错误。

当在注册表中查找不存在的CWE条目时返回此错误。

func NewCWENotFoundError

func NewCWENotFoundError(id int) *CWENotFoundError

NewCWENotFoundError 创建一个新的CWENotFoundError。

参数:

  • id: 未找到的CWE ID

type CWEsResponse

type CWEsResponse struct {
	// Data 包含CWE数据的原始JSON
	Data json.RawMessage `json:"Data"`
	// Weaknesses 弱点映射表,键为CWE ID
	Weaknesses map[string]*CWE `json:"weaknesses,omitempty"`
}

CWEsResponse 是批量CWE查询API的响应结构。

type CategoriesResponse

type CategoriesResponse struct {
	// Data 包含类别数据的原始JSON
	Data json.RawMessage `json:"Data,omitempty"`
	// Categories 类别列表
	Categories []Category `json:"categories,omitempty"`
}

CategoriesResponse 是类别查询API的响应结构。

type Category

type Category struct {
	// ID 类别的数字标识符
	ID int `json:"id" xml:"ID,attr"`
	// Name 类别名称
	Name string `json:"name" xml:"Name"`
	// Status 状态
	Status Status `json:"status,omitempty" xml:"Status,omitempty"`
	// Description 类别描述
	Description string `json:"description" xml:"Description"`
	// Relationships 关系列表
	Relationships []Relationship `json:"relationships,omitempty" xml:"Relationships>Relationship,omitempty"`
	// Notes 备注信息
	Notes string `json:"notes,omitempty" xml:"Notes,omitempty"`
	// References 参考文献列表
	References []Reference `json:"references,omitempty" xml:"References>Reference,omitempty"`
	// ContentHistory 内容历史
	ContentHistory *ContentHistory `json:"content_history,omitempty" xml:"ContentHistory,omitempty"`
}

Category 表示CWE类别条目。

类别是一种CWE条目类型,用于将相关的弱点分组归类。

func NewCategory

func NewCategory(id int, name string) *Category

NewCategory 创建一个新的CWE类别条目。

参数:

  • id: 类别的数字标识符
  • name: 类别名称

返回值:

  • *Category: 新创建的类别实例

type CompoundElement

type CompoundElement struct {
	// ID 复合元素的数字标识符
	ID int `json:"id" xml:"ID,attr"`
	// Name 复合元素名称
	Name string `json:"name" xml:"Name"`
	// Structure 结构类型(Chain或Composite)
	Structure Structure `json:"structure" xml:"Structure"`
	// Status 状态
	Status Status `json:"status,omitempty" xml:"Status,omitempty"`
	// Description 复合元素描述
	Description string `json:"description" xml:"Description"`
	// Relationships 关系列表
	Relationships []Relationship `json:"relationships,omitempty" xml:"Relationships>Relationship,omitempty"`
}

CompoundElement 表示CWE复合元素条目。

复合元素是一种CWE条目类型,描述了由多个弱点组合而成的复合弱点, 包括链式弱点和复合弱点。

func NewCompoundElement

func NewCompoundElement(id int, name string, structure Structure) *CompoundElement

NewCompoundElement 创建一个新的CWE复合元素条目。

参数:

  • id: 复合元素的数字标识符
  • name: 复合元素名称
  • structure: 结构类型

返回值:

  • *CompoundElement: 新创建的复合元素实例

type Consequence

type Consequence struct {
	// Scopes 受影响的安全范围列表,如机密性、完整性、可用性等
	Scopes []ConsequenceScope `json:"scopes" xml:"Scopes>Scope"`
	// Impacts 影响严重程度列表,如高、中、低
	Impacts []ConsequenceImpact `json:"impacts,omitempty" xml:"Impacts>Impact,omitempty"`
	// Likelihood 此后果被利用的可能性
	Likelihood LikelihoodOfExploit `json:"likelihood,omitempty" xml:"Likelihood,omitempty"`
	// Note 关于后果的补充说明
	Note string `json:"note,omitempty" xml:"Note,omitempty"`
}

Consequence 表示CWE条目可能造成的后果。

每个后果包含影响范围、影响严重程度、利用可能性和备注信息。 一个CWE条目可以有多种不同的后果,每种后果可能影响不同的范围。

func (*Consequence) HasImpact

func (c *Consequence) HasImpact(impact ConsequenceImpact) bool

HasImpact 检查后果是否包含指定的影响严重程度。

参数:

  • impact: 需要检查的影响严重程度

返回值:

  • bool: 如果后果中包含该影响严重程度返回true,否则返回false

func (*Consequence) HasScope

func (c *Consequence) HasScope(scope ConsequenceScope) bool

HasScope 检查后果是否包含指定的安全范围。

参数:

  • scope: 需要检查的安全范围

返回值:

  • bool: 如果后果中包含该安全范围返回true,否则返回false

func (*Consequence) MaxImpact

func (c *Consequence) MaxImpact() ConsequenceImpact

MaxImpact 返回后果中最高的影响严重程度。

影响严重程度的排序为:High > Medium > Low > Unknown。 如果Impacts列表为空,返回ImpactUnknown。

返回值:

  • ConsequenceImpact: 最高的影响严重程度

func (*Consequence) Validate

func (c *Consequence) Validate() error

Validate 验证后果的有效性。

检查条件:

  • Scopes列表至少包含一个范围

返回值:

  • error: 如果验证失败返回ValidationError,否则返回nil

type ConsequenceImpact

type ConsequenceImpact string

ConsequenceImpact 表示后果的影响严重程度。

const (
	ImpactHigh    ConsequenceImpact = "High"
	ImpactMedium  ConsequenceImpact = "Medium"
	ImpactLow     ConsequenceImpact = "Low"
	ImpactUnknown ConsequenceImpact = "Unknown"
)

func AllConsequenceImpactValues

func AllConsequenceImpactValues() []ConsequenceImpact

AllConsequenceImpactValues 返回所有有效的影响严重程度值。

func ParseConsequenceImpact

func ParseConsequenceImpact(s string) (ConsequenceImpact, error)

ParseConsequenceImpact 从字符串解析影响严重程度。

func (ConsequenceImpact) ImpactOrder

func (i ConsequenceImpact) ImpactOrder() int

ImpactOrder 返回影响严重程度的排序权重。 High=4, Medium=3, Low=2, Unknown=1, 未知=0

func (ConsequenceImpact) IsValid

func (i ConsequenceImpact) IsValid() bool

IsValid 检查影响严重程度是否为有效值。

func (ConsequenceImpact) String

func (i ConsequenceImpact) String() string

String 返回影响严重程度的字符串表示。

type ConsequenceScope

type ConsequenceScope string

ConsequenceScope 表示后果的影响范围。

const (
	ScopeConfidentiality ConsequenceScope = "Confidentiality"
	ScopeIntegrity       ConsequenceScope = "Integrity"
	ScopeAvailability    ConsequenceScope = "Availability"
	ScopeAccessControl   ConsequenceScope = "Access Control"
	ScopeAccountability  ConsequenceScope = "Accountability"
	ScopeAuthentication  ConsequenceScope = "Authentication"
	ScopeAuthorization   ConsequenceScope = "Authorization"
	ScopeNonRepudiation  ConsequenceScope = "Non-Repudiation"
)

func AllConsequenceScopeValues

func AllConsequenceScopeValues() []ConsequenceScope

AllConsequenceScopeValues 返回所有有效的影响范围值。

func ParseConsequenceScope

func ParseConsequenceScope(s string) (ConsequenceScope, error)

ParseConsequenceScope 从字符串解析影响范围。

func (ConsequenceScope) IsValid

func (s ConsequenceScope) IsValid() bool

IsValid 检查影响范围是否为有效值。

func (ConsequenceScope) String

func (s ConsequenceScope) String() string

String 返回影响范围的字符串表示。

type ConsequenceScopeCount

type ConsequenceScopeCount struct {
	// Scope 后果范围
	Scope ConsequenceScope `json:"scope"`
	// Count 出现次数
	Count int `json:"count"`
}

ConsequenceScopeCount 表示后果范围的统计计数。

type ContentHistory

type ContentHistory struct {
	// Submission 提交信息
	Submission *HistoryEntry `json:"submission,omitempty" xml:"Submission,omitempty"`
	// Modifications 修改记录列表
	Modifications []HistoryEntry `json:"modifications,omitempty" xml:"Modifications>Modification,omitempty"`
}

ContentHistory 表示CWE条目的内容历史。

内容历史记录了CWE条目的提交和修改记录。

type DataFetcher

type DataFetcher interface {
	// Fetch 获取指定ID的CWE条目
	Fetch(ctx context.Context, id int) (*CWE, error)
}

DataFetcher 定义CWE数据获取的接口。

该接口抽象了CWE数据的获取方式,允许上层应用 根据需要选择API获取或本地注册表查找等不同实现。

type DemonstrativeExample

type DemonstrativeExample struct {
	// IntroText 示例的介绍文本
	IntroText string `json:"intro_text,omitempty" xml:"IntroText,omitempty"`
	// BodyText 示例的主体内容
	BodyText string `json:"body_text,omitempty" xml:"BodyText,omitempty"`
}

DemonstrativeExample 表示示范性示例。

示范性示例展示了该弱点在实际中可能出现的情况。

type Effectiveness

type Effectiveness string

Effectiveness 表示缓解措施或检测方法的有效性。

const (
	EffectivenessHigh           Effectiveness = "High"
	EffectivenessModerate       Effectiveness = "Moderate"
	EffectivenessLimited        Effectiveness = "Limited"
	EffectivenessDefenseInDepth Effectiveness = "Defense in Depth"
	EffectivenessSOARPartial    Effectiveness = "SOAR Partial"
	EffectivenessUnknown        Effectiveness = "Unknown"
)

func AllEffectivenessValues

func AllEffectivenessValues() []Effectiveness

AllEffectivenessValues 返回所有有效的有效性值。

func ParseEffectiveness

func ParseEffectiveness(s string) (Effectiveness, error)

ParseEffectiveness 从字符串解析有效性。

func (Effectiveness) IsValid

func (e Effectiveness) IsValid() bool

IsValid 检查有效性是否为有效值。

func (Effectiveness) String

func (e Effectiveness) String() string

String 返回有效性的字符串表示。

type FilterOption

type FilterOption struct {
	// Abstraction 按抽象层级过滤
	Abstraction Abstraction
	// Status 按状态过滤
	Status Status
	// Structure 按结构类型过滤
	Structure Structure
	// Likelihood 按利用可能性过滤
	Likelihood LikelihoodOfExploit
	// MinID 按最小CWE ID过滤(包含)
	MinID int
	// MaxID 按最大CWE ID过滤(包含)
	MaxID int
	// Keyword 按关键字过滤(匹配名称和描述,不区分大小写)
	Keyword string
	// Scope 按后果范围过滤
	Scope ConsequenceScope
}

FilterOption 定义CWE条目的过滤选项。

多个FilterOption可以组合使用,所有非零值的选项都会作为过滤条件, 各条件之间是AND(与)关系。

type HTTPClient

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

HTTPClient 提供带有重试、速率限制和超时控制的HTTP客户端。

该客户端封装了标准的http.Client,添加了以下功能:

  • 自动重试:对5xx错误自动重试
  • 速率限制:通过RateLimiter控制请求频率
  • 超时控制:通过context控制请求超时
  • User-Agent:自动添加SDK版本标识

示例:

client := cwe.NewHTTPClient("https://cwe-api.mitre.org/api/v1",
    cwe.WithRetry(3, 5*time.Second),
    cwe.WithHTTPRateLimiter(1.0, 5),
    cwe.WithHTTPTimeout(30*time.Second),
)
defer client.Close()

func NewHTTPClient

func NewHTTPClient(baseURL string, opts ...HTTPClientOption) *HTTPClient

NewHTTPClient 创建一个新的HTTPClient实例。

参数:

  • baseURL: API基础URL
  • opts: 可选的配置选项

返回值:

  • *HTTPClient: 新创建的HTTPClient实例

func (*HTTPClient) Close

func (c *HTTPClient) Close()

Close 关闭HTTP客户端,释放资源。

func (*HTTPClient) Get

func (c *HTTPClient) Get(ctx context.Context, path string, result interface{}) error

Get 发送GET请求并解析JSON响应。

该方法自动处理速率限制、重试和错误响应。 响应体会被自动解析到result参数指向的结构体中。

参数:

  • ctx: 请求上下文,用于取消和超时控制
  • path: 请求路径(相对于baseURL)
  • result: 用于存储解析结果的指针

返回值:

  • error: 请求失败时返回APIError或其他错误

func (*HTTPClient) GetBaseURL

func (c *HTTPClient) GetBaseURL() string

GetBaseURL 获取基础URL。

func (*HTTPClient) GetHTTPClient

func (c *HTTPClient) GetHTTPClient() *http.Client

GetHTTPClient 获取底层的http.Client。

func (*HTTPClient) GetMaxRetries

func (c *HTTPClient) GetMaxRetries() int

GetMaxRetries 获取最大重试次数。

func (*HTTPClient) GetRateLimiter

func (c *HTTPClient) GetRateLimiter() *RateLimiter

GetRateLimiter 获取速率限制器。

func (*HTTPClient) GetRaw

func (c *HTTPClient) GetRaw(ctx context.Context, path string) ([]byte, error)

GetRaw 发送GET请求并返回原始响应体。

参数:

  • ctx: 请求上下文
  • path: 请求路径

返回值:

  • []byte: 响应体
  • error: 请求失败时返回错误

func (*HTTPClient) GetRetryDelay

func (c *HTTPClient) GetRetryDelay() time.Duration

GetRetryDelay 获取重试间隔时间。

func (*HTTPClient) Post

func (c *HTTPClient) Post(ctx context.Context, path string, body interface{}, result interface{}) error

Post 发送POST请求并解析JSON响应。

参数:

  • ctx: 请求上下文
  • path: 请求路径
  • body: 请求体(会被序列化为JSON)
  • result: 用于存储解析结果的指针

返回值:

  • error: 请求失败时返回错误

func (*HTTPClient) PostForm

func (c *HTTPClient) PostForm(ctx context.Context, path string, data url.Values, result interface{}) error

PostForm 发送POST表单请求。

参数:

  • ctx: 请求上下文
  • path: 请求路径
  • data: 表单数据
  • result: 用于存储解析结果的指针

返回值:

  • error: 请求失败时返回错误

func (*HTTPClient) SetBaseURL

func (c *HTTPClient) SetBaseURL(url string)

SetBaseURL 设置基础URL。

func (*HTTPClient) SetHTTPClient

func (c *HTTPClient) SetHTTPClient(client *http.Client)

SetHTTPClient 设置底层的http.Client。

func (*HTTPClient) SetMaxRetries

func (c *HTTPClient) SetMaxRetries(maxRetries int)

SetMaxRetries 设置最大重试次数。

func (*HTTPClient) SetRateLimiter

func (c *HTTPClient) SetRateLimiter(limiter *RateLimiter)

SetRateLimiter 设置速率限制器。

func (*HTTPClient) SetRetryDelay

func (c *HTTPClient) SetRetryDelay(delay time.Duration)

SetRetryDelay 设置重试间隔时间。

type HTTPClientOption

type HTTPClientOption func(*HTTPClient)

HTTPClientOption 是HTTPClient的配置选项函数类型

func WithHTTPClient

func WithHTTPClient(client *http.Client) HTTPClientOption

WithHTTPClient 设置自定义的http.Client。

参数:

  • client: 自定义的http.Client实例

func WithHTTPRateLimiter

func WithHTTPRateLimiter(rate float64, burst int) HTTPClientOption

WithHTTPRateLimiter 设置HTTP请求的速率限制器。

参数:

  • rate: 每秒允许的请求数
  • burst: 允许的突发请求数

func WithHTTPTimeout

func WithHTTPTimeout(timeout time.Duration) HTTPClientOption

WithHTTPTimeout 设置HTTP请求的超时时间。

参数:

  • timeout: 请求超时时间

func WithRetry

func WithRetry(maxRetries int, delay time.Duration) HTTPClientOption

WithRetry 设置HTTP请求的重试次数和重试间隔。

参数:

  • maxRetries: 最大重试次数(不包括首次请求),0表示不重试
  • delay: 重试间隔时间

func WithUserAgent

func WithUserAgent(ua string) HTTPClientOption

WithUserAgent 设置HTTP请求的User-Agent头。

参数:

  • ua: User-Agent字符串

type HistoryEntry

type HistoryEntry struct {
	// Name 提交者或修改者姓名
	Name string `json:"name,omitempty" xml:"Name,omitempty"`
	// Organization 所属组织
	Organization string `json:"organization,omitempty" xml:"Organization,omitempty"`
	// Date 日期
	Date string `json:"date,omitempty" xml:"Date,omitempty"`
	// Comment 注释
	Comment string `json:"comment,omitempty" xml:"Comment,omitempty"`
}

HistoryEntry 表示历史条目。

历史条目记录了CWE条目的提交者或修改者信息。

type Introduction

type Introduction struct {
	// Phase 引入阶段
	Phase IntroductionPhase `json:"phase" xml:"Phase"`
	// Description 引入方式的描述
	Description string `json:"description,omitempty" xml:"Description,omitempty"`
}

Introduction 表示弱点的引入方式。

引入方式描述了弱点在哪个阶段被引入到软件中。

type IntroductionPhase

type IntroductionPhase string

IntroductionPhase 表示弱点引入的阶段。

const (
	PhaseArchitectureAndDesign IntroductionPhase = "Architecture and Design"
	PhaseImplementation        IntroductionPhase = "Implementation"
	PhaseBuildAndCompilation   IntroductionPhase = "Build and Compilation"
	PhaseOperation             IntroductionPhase = "Operation"
	PhaseSystemConfiguration   IntroductionPhase = "System Configuration"
	PhaseInstallation          IntroductionPhase = "Installation"
	PhasePolicy                IntroductionPhase = "Policy"
)

func AllIntroductionPhaseValues

func AllIntroductionPhaseValues() []IntroductionPhase

AllIntroductionPhaseValues 返回所有有效的引入阶段值。

func ParseIntroductionPhase

func ParseIntroductionPhase(s string) (IntroductionPhase, error)

ParseIntroductionPhase 从字符串解析引入阶段。

func (IntroductionPhase) IsValid

func (p IntroductionPhase) IsValid() bool

IsValid 检查引入阶段是否为有效值。

func (IntroductionPhase) String

func (p IntroductionPhase) String() string

String 返回引入阶段的字符串表示。

type InvalidCWEIDError

type InvalidCWEIDError struct {
	*CWEError
	// ID 无效的CWE ID输入
	ID string
}

InvalidCWEIDError 表示CWE ID格式无效的错误。

当CWE ID不符合 "CWE-NNN" 格式或数字部分无效时返回此错误。

func NewInvalidCWEIDError

func NewInvalidCWEIDError(id string) *InvalidCWEIDError

NewInvalidCWEIDError 创建一个新的InvalidCWEIDError。

参数:

  • id: 无效的CWE ID字符串

type LikelihoodOfExploit

type LikelihoodOfExploit string

LikelihoodOfExploit 表示漏洞被利用的可能性。

const (
	LikelihoodHigh    LikelihoodOfExploit = "High"
	LikelihoodMedium  LikelihoodOfExploit = "Medium"
	LikelihoodLow     LikelihoodOfExploit = "Low"
	LikelihoodUnknown LikelihoodOfExploit = "Unknown"
)

func AllLikelihoodOfExploitValues

func AllLikelihoodOfExploitValues() []LikelihoodOfExploit

AllLikelihoodOfExploitValues 返回所有有效的利用可能性值。

func ParseLikelihoodOfExploit

func ParseLikelihoodOfExploit(s string) (LikelihoodOfExploit, error)

ParseLikelihoodOfExploit 从字符串解析利用可能性。

func (LikelihoodOfExploit) IsValid

func (l LikelihoodOfExploit) IsValid() bool

IsValid 检查利用可能性是否为有效值。

func (LikelihoodOfExploit) LikelihoodOrder

func (l LikelihoodOfExploit) LikelihoodOrder() int

LikelihoodOrder 返回利用可能性的排序权重。 High=4, Medium=3, Low=2, Unknown=1, 未知=0

func (LikelihoodOfExploit) String

func (l LikelihoodOfExploit) String() string

String 返回利用可能性的字符串表示。

type Mitigation

type Mitigation struct {
	// Phase 缓解措施适用的阶段
	Phase MitigationPhase `json:"phase,omitempty" xml:"Phase,omitempty"`
	// Strategy 缓解策略名称
	Strategy string `json:"strategy,omitempty" xml:"Strategy,omitempty"`
	// Description 缓解措施的详细描述
	Description string `json:"description" xml:"Description"`
	// Effectiveness 缓解措施的有效性
	Effectiveness Effectiveness `json:"effectiveness,omitempty" xml:"Effectiveness,omitempty"`
}

Mitigation 表示缓解措施。

缓解措施描述了如何减少或消除特定弱点的风险。

type MitigationPhase

type MitigationPhase string

MitigationPhase 表示缓解措施的阶段。

const (
	MitigationPhaseArchitectureAndDesign MitigationPhase = "Architecture and Design"
	MitigationPhaseBuildAndCompilation   MitigationPhase = "Build and Compilation"
	MitigationPhaseImplementation        MitigationPhase = "Implementation"
	MitigationPhaseOperation             MitigationPhase = "Operation"
	MitigationPhaseSystemConfiguration   MitigationPhase = "System Configuration"
	MitigationPhaseInstallation          MitigationPhase = "Installation"
	MitigationPhasePolicy                MitigationPhase = "Policy"
)

func AllMitigationPhaseValues

func AllMitigationPhaseValues() []MitigationPhase

AllMitigationPhaseValues 返回所有有效的缓解措施阶段值。

func ParseMitigationPhase

func ParseMitigationPhase(s string) (MitigationPhase, error)

ParseMitigationPhase 从字符串解析缓解措施阶段。

func (MitigationPhase) IsValid

func (m MitigationPhase) IsValid() bool

IsValid 检查缓解措施阶段是否为有效值。

func (MitigationPhase) String

func (m MitigationPhase) String() string

String 返回缓解措施阶段的字符串表示。

type MultipleFetcher

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

MultipleFetcher 批量获取CWE条目的获取器。

func NewMultipleFetcher

func NewMultipleFetcher(client *APIClient) *MultipleFetcher

NewMultipleFetcher 创建一个新的批量获取器。

func (*MultipleFetcher) FetchMultiple

func (f *MultipleFetcher) FetchMultiple(ctx context.Context, ids []int) (map[string]*CWE, error)

FetchMultiple 批量获取多个CWE弱点条目。

参数:

  • ctx: 请求上下文
  • ids: 要获取的CWE ID列表

返回值:

  • map[string]*CWE: 以CWE ID字符串为键的弱点映射
  • error: 获取失败时返回错误

func (*MultipleFetcher) FetchMultipleToRegistry

func (f *MultipleFetcher) FetchMultipleToRegistry(ctx context.Context, ids []int, registry *Registry) error

FetchMultipleToRegistry 批量获取CWE弱点条目并注册到Registry中。

参数:

  • ctx: 请求上下文
  • ids: 要获取的CWE ID列表
  • registry: 目标注册表

返回值:

  • error: 获取或注册失败时返回错误
type Navigator struct {
	// contains filtered or unexported fields
}

Navigator 提供CWE条目之间的关系导航功能。

Navigator基于Registry中的数据,提供丰富的关系遍历能力, 包括层级导航、顺序导航、依赖导航和对等导航等。

使用场景:

  • 分析弱点的上游和下游关系
  • 查找链式攻击路径
  • 识别复合弱点的组成要素
  • 计算弱点之间的关系距离

示例:

registry := cwe.NewRegistry()
// ... 注册CWE数据并构建索引 ...
nav := cwe.NewNavigator(registry)
parents := nav.Parents(79)
ancestors := nav.Ancestors(79)

func NewNavigator

func NewNavigator(r *Registry) *Navigator

NewNavigator 创建一个新的关系导航器。

参数:

  • r: 已构建索引的CWE注册表
func (n *Navigator) Ancestors(id int) []*CWE

Ancestors 递归获取指定CWE条目的所有祖先条目。

func (n *Navigator) CanAlsoBe(id int) []*CWE

CanAlsoBe 获取指定CWE条目也可以被视为的条目。

func (n *Navigator) CanFollow(id int) []*CWE

CanFollow 获取指定CWE条目可以后随的条目(链式后继)。

func (n *Navigator) CanPrecede(id int) []*CWE

CanPrecede 获取指定CWE条目可以前置的条目(链式前驱)。

func (n *Navigator) ChainMembers(id int) []*CWE

ChainMembers 获取指定链式复合元素的所有链成员。

func (n *Navigator) Children(id int) []*CWE

Children 获取指定CWE条目的直接子级条目列表。

func (n *Navigator) CompositeMembers(id int) []*CWE

CompositeMembers 获取指定复合元素的所有组合成员。

func (n *Navigator) Descendants(id int) []*CWE

Descendants 递归获取指定CWE条目的所有后代条目。

func (n *Navigator) IsAncestorOf(ancestor, descendant int) bool

IsAncestorOf 检查ancestor是否是descendant的祖先。

func (n *Navigator) IsDescendantOf(descendant, ancestor int) bool

IsDescendantOf 检查descendant是否是ancestor的后代。

func (n *Navigator) IsRelated(a, b int) bool

IsRelated 检查两个CWE条目是否存在任何关系。

func (n *Navigator) Parents(id int) []*CWE

Parents 获取指定CWE条目的直接父级条目列表。

func (n *Navigator) Peers(id int) []*CWE

Peers 获取指定CWE条目的对等条目。

func (n *Navigator) RelationshipDepth(ancestor, descendant int) int

RelationshipDepth 计算两个CWE条目之间的层级关系深度。

如果两者不存在层级关系,返回-1。 直接的父子关系深度为1。

func (n *Navigator) RequiredBy(id int) []*CWE

RequiredBy 获取需要指定CWE条目的条目。

func (n *Navigator) Requires(id int) []*CWE

Requires 获取指定CWE条目所需的条目(复合依赖)。

func (n *Navigator) ShortestPath(from, to int) []int

ShortestPath 查找两个CWE条目之间的最短路径。

使用广度优先搜索在关系图中查找从from到to的最短路径。 返回的路径包含起点和终点。

参数:

  • from: 起始CWE ID
  • to: 目标CWE ID

返回值:

  • []int: 路径上的CWE ID列表,如果不存在路径返回nil
func (n *Navigator) Siblings(id int) []*CWE

Siblings 获取指定CWE条目的兄弟条目(具有相同父级的条目)。

func (n *Navigator) String() string

String 返回导航器的字符串表示。

type ObservedExample

type ObservedExample struct {
	// Reference 参考编号
	Reference string `json:"reference,omitempty" xml:"Reference,omitempty"`
	// Description 示例描述
	Description string `json:"description" xml:"Description"`
	// Link 相关链接
	Link string `json:"link,omitempty" xml:"Link,omitempty"`
}

ObservedExample 表示观察到的真实示例。

观察到的示例来自真实的漏洞报告或安全事件。

type ParseError

type ParseError struct {
	*CWEError
	// Offset 解析失败的位置偏移量
	Offset int64
}

ParseError 表示解析失败的错误。

当XML、JSON或其他格式的数据解析失败时返回此错误。

func NewParseError

func NewParseError(detail string, offset int64) *ParseError

NewParseError 创建一个新的ParseError。

参数:

  • detail: 解析失败的详细描述
  • offset: 解析失败的位置偏移量

type PlatformEntry

type PlatformEntry struct {
	// Name 平台名称
	Name string `json:"name" xml:"Name,attr"`
	// Prevalence 使用普遍程度
	Prevalence Prevalence `json:"prevalence,omitempty" xml:"Prevalence,attr,omitempty"`
}

PlatformEntry 表示平台条目。

每个平台条目包含名称和使用普遍程度。

type PlatformType

type PlatformType string

PlatformType 表示适用平台的类型。

const (
	PlatformLanguage        PlatformType = "Language"
	PlatformOperatingSystem PlatformType = "Operating System"
	PlatformArchitecture    PlatformType = "Architecture"
	PlatformTechnology      PlatformType = "Technology"
)

func AllPlatformTypeValues

func AllPlatformTypeValues() []PlatformType

AllPlatformTypeValues 返回所有有效的平台类型值。

func ParsePlatformType

func ParsePlatformType(s string) (PlatformType, error)

ParsePlatformType 从字符串解析平台类型。

func (PlatformType) IsValid

func (p PlatformType) IsValid() bool

IsValid 检查平台类型是否为有效值。

func (PlatformType) String

func (p PlatformType) String() string

String 返回平台类型的字符串表示。

type Prevalence

type Prevalence string

Prevalence 表示平台的使用普遍程度。

const (
	PrevalenceOften        Prevalence = "Often"
	PrevalenceSometimes    Prevalence = "Sometimes"
	PrevalenceRarely       Prevalence = "Rarely"
	PrevalenceUndetermined Prevalence = "Undetermined"
)

func AllPrevalenceValues

func AllPrevalenceValues() []Prevalence

AllPrevalenceValues 返回所有有效的普遍程度值。

func ParsePrevalence

func ParsePrevalence(s string) (Prevalence, error)

ParsePrevalence 从字符串解析普遍程度。

func (Prevalence) IsValid

func (p Prevalence) IsValid() bool

IsValid 检查普遍程度是否为有效值。

func (Prevalence) String

func (p Prevalence) String() string

String 返回普遍程度的字符串表示。

type RateLimitError

type RateLimitError struct {
	*CWEError
	// RetryAfter 建议等待的时间
	RetryAfter time.Duration
}

RateLimitError 表示请求速率超限的错误。

当请求频率超过API速率限制时返回此错误。

func NewRateLimitError

func NewRateLimitError(retryAfter time.Duration) *RateLimitError

NewRateLimitError 创建一个新的RateLimitError。

参数:

  • retryAfter: 建议等待的时间

type RateLimiter

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

RateLimiter 实现了一个基于令牌桶算法的速率限制器。

该速率限制器使用令牌桶算法控制请求频率, 适用于对MITRE CWE API等外部服务进行速率限制。 本实现仅使用Go标准库,不依赖任何第三方包。

使用场景:

  • 限制对MITRE CWE API的请求频率
  • 防止因请求过快而被外部服务拒绝
  • 控制并发请求的速率

示例:

limiter := cwe.NewRateLimiter(1.0, 5)  // 每秒1个请求,突发5个
if limiter.Allow() {
    // 执行请求
} else {
    // 等待
    limiter.Wait(context.Background())
}

func NewRateLimiter

func NewRateLimiter(rate float64, burst int) *RateLimiter

NewRateLimiter 创建一个新的速率限制器。

参数:

  • rate: 每秒允许的请求数。例如1.0表示每秒1个请求,0.1表示每10秒1个请求。
  • burst: 允许的突发请求数。当令牌桶满时,可以一次性发送burst个请求。

返回值:

  • *RateLimiter: 新创建的速率限制器

示例:

// 每秒1个请求,最多突发5个
limiter := cwe.NewRateLimiter(1.0, 5)

// 每10秒1个请求(MITRE API默认限制)
limiter := cwe.NewRateLimiter(0.1, 1)

func (*RateLimiter) Allow

func (r *RateLimiter) Allow() bool

Allow 检查是否允许立即执行请求(非阻塞)。

如果令牌桶中有可用令牌,消耗一个令牌并返回true。 如果没有可用令牌,返回false,不消耗令牌。

返回值:

  • bool: 如果允许请求返回true,否则返回false

func (*RateLimiter) GetBurst

func (r *RateLimiter) GetBurst() int

GetBurst 获取允许的突发请求数。

返回值:

  • int: 允许的突发请求数

func (*RateLimiter) GetInterval

func (r *RateLimiter) GetInterval() time.Duration

GetInterval 获取请求间隔时间。

返回值:

  • time.Duration: 两次请求之间的最小间隔时间

func (*RateLimiter) GetRate

func (r *RateLimiter) GetRate() float64

GetRate 获取每秒允许的请求数。

返回值:

  • float64: 每秒允许的请求数

func (*RateLimiter) ResetLastRequest

func (r *RateLimiter) ResetLastRequest()

ResetLastRequest 重置上次请求时间。

调用此方法后,下一次WaitForRequest将立即返回, 而不需要等待间隔时间。

func (*RateLimiter) SetInterval

func (r *RateLimiter) SetInterval(interval time.Duration)

SetInterval 设置请求间隔时间。

参数:

  • interval: 两次请求之间的最小间隔时间

func (*RateLimiter) Tokens

func (r *RateLimiter) Tokens() float64

Tokens 返回当前可用的令牌数。

返回值:

  • float64: 当前可用的令牌数

func (*RateLimiter) Wait

func (r *RateLimiter) Wait(ctx context.Context) error

Wait 阻塞等待直到可以执行请求,或上下文被取消。

如果令牌桶中没有可用令牌,该函数会等待直到有令牌可用。 可以通过context来取消等待。

参数:

  • ctx: 用于取消等待的上下文

返回值:

  • error: 如果等待被取消返回context的错误,否则返回nil

func (*RateLimiter) WaitForRequest

func (r *RateLimiter) WaitForRequest()

WaitForRequest 阻塞等待直到可以执行请求(兼容旧接口)。

该方法使用请求间隔模式,确保两次请求之间至少间隔指定的时间。 如果这是第一次请求,立即返回。

type Reference

type Reference struct {
	// ID 参考文献的标识符
	ID int `json:"id,omitempty" xml:"Reference_ID,omitempty"`
	// Author 作者
	Author string `json:"author,omitempty" xml:"Author,omitempty"`
	// Title 标题
	Title string `json:"title" xml:"Title"`
	// URL 链接地址
	URL string `json:"url,omitempty" xml:"URL,omitempty"`
}

Reference 表示参考文献。

参考文献提供了关于该弱点的更多信息来源。

type Registry

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

Registry 是CWE条目的内存注册表。

Registry提供了CWE条目的存储、索引和查询功能。 它是本地数据管理的核心组件,支持:

  • 注册和查找CWE弱点、类别、视图、复合元素
  • 构建关系索引(父子关系、对等关系等)
  • 导出和导入JSON数据
  • 并发安全的读写操作

使用场景:

  • 从XML目录加载离线CWE数据
  • 缓存API查询结果
  • 构建CWE关系图

示例:

registry := cwe.NewRegistry()
registry.Register(&cwe.CWE{ID: 79, Name: "XSS", Abstraction: cwe.AbstractionBase})
cwe79, found := registry.Get(79)

func NewRegistry

func NewRegistry() *Registry

NewRegistry 创建一个新的空Registry实例。

func (*Registry) BuildIndexes

func (r *Registry) BuildIndexes()

BuildIndexes 构建关系索引。

该方法遍历所有CWE条目的关系数据,构建以下索引:

  • 父子关系索引(基于ChildOf/ParentOf关系)
  • 对等关系索引(基于PeerOf/CanAlsoBe关系)
  • 成员关系索引(基于类别/视图的成员列表)

构建索引后,GetParentIDs、GetChildIDs、GetAncestorIDs等方法 可以快速返回结果。建议在数据加载完成后调用此方法。

func (*Registry) CategoryCount

func (r *Registry) CategoryCount() int

CategoryCount 获取注册表中类别的数量。

func (*Registry) Clear

func (r *Registry) Clear()

Clear 清空注册表中的所有数据。

func (*Registry) CompoundElementCount

func (r *Registry) CompoundElementCount() int

CompoundElementCount 获取注册表中复合元素的数量。

func (*Registry) Contains

func (r *Registry) Contains(id int) bool

Contains 检查注册表中是否包含指定ID的CWE条目。

func (*Registry) ExportCSV

func (r *Registry) ExportCSV() ([]byte, error)

ExportCSV 将注册表中的CWE弱点导出为CSV格式。

func (*Registry) ExportJSON

func (r *Registry) ExportJSON() ([]byte, error)

ExportJSON 将注册表数据导出为JSON格式。

func (*Registry) Get

func (r *Registry) Get(id int) (*CWE, bool)

Get 根据ID获取CWE弱点条目。

func (*Registry) GetAll

func (r *Registry) GetAll() []*CWE

GetAll 获取所有CWE弱点条目。

func (*Registry) GetAllCategories

func (r *Registry) GetAllCategories() []*Category

GetAllCategories 获取所有CWE类别。

func (*Registry) GetAllViews

func (r *Registry) GetAllViews() []*View

GetAllViews 获取所有CWE视图。

func (*Registry) GetAncestorIDs

func (r *Registry) GetAncestorIDs(id int) []int

GetAncestorIDs 递归获取指定CWE条目的所有祖先ID。

需要先调用BuildIndexes构建索引。 该方法使用广度优先搜索遍历父级关系,避免循环引用导致的无限递归。

func (*Registry) GetCategory

func (r *Registry) GetCategory(id int) (*Category, bool)

GetCategory 根据ID获取CWE类别。

func (*Registry) GetCategoryMembers

func (r *Registry) GetCategoryMembers(categoryID int) []int

GetCategoryMembers 获取指定类别的成员ID列表。

func (*Registry) GetChildIDs

func (r *Registry) GetChildIDs(id int) []int

GetChildIDs 获取指定CWE条目的子级ID列表。

需要先调用BuildIndexes构建索引。

func (*Registry) GetCompoundElement

func (r *Registry) GetCompoundElement(id int) (*CompoundElement, bool)

GetCompoundElement 根据ID获取复合元素。

func (*Registry) GetDescendantIDs

func (r *Registry) GetDescendantIDs(id int) []int

GetDescendantIDs 递归获取指定CWE条目的所有后代ID。

需要先调用BuildIndexes构建索引。 该方法使用广度优先搜索遍历子级关系,避免循环引用导致的无限递归。

func (*Registry) GetMemberOfIDs

func (r *Registry) GetMemberOfIDs(id int) []int

GetMemberOfIDs 获取指定CWE条目所属的类别/视图ID列表。

func (*Registry) GetParentIDs

func (r *Registry) GetParentIDs(id int) []int

GetParentIDs 获取指定CWE条目的父级ID列表。

需要先调用BuildIndexes构建索引。

func (*Registry) GetPeerIDs

func (r *Registry) GetPeerIDs(id int) []int

GetPeerIDs 获取指定CWE条目的对等ID列表。

需要先调用BuildIndexes构建索引。

func (*Registry) GetView

func (r *Registry) GetView(id int) (*View, bool)

GetView 根据ID获取CWE视图。

func (*Registry) GetViewMembers

func (r *Registry) GetViewMembers(viewID int) []int

GetViewMembers 获取指定视图的成员ID列表。

func (*Registry) ImportJSON

func (r *Registry) ImportJSON(jsonData []byte) error

ImportJSON 从JSON格式导入数据到注册表。

func (*Registry) IndexesBuilt

func (r *Registry) IndexesBuilt() bool

IndexesBuilt 检查索引是否已构建。

func (*Registry) Register

func (r *Registry) Register(cwe *CWE) error

Register 向注册表中注册一个CWE弱点条目。

如果ID已存在,返回ValidationError。

参数:

  • cwe: 要注册的CWE条目

返回值:

  • error: 注册失败时返回错误

func (*Registry) RegisterCategory

func (r *Registry) RegisterCategory(cat *Category) error

RegisterCategory 向注册表中注册一个CWE类别。

func (*Registry) RegisterCompoundElement

func (r *Registry) RegisterCompoundElement(ce *CompoundElement) error

RegisterCompoundElement 向注册表中注册一个复合元素。

func (*Registry) RegisterView

func (r *Registry) RegisterView(view *View) error

RegisterView 向注册表中注册一个CWE视图。

func (*Registry) Remove

func (r *Registry) Remove(id int) error

Remove 从注册表中移除指定ID的CWE条目。

func (*Registry) RemoveCategory

func (r *Registry) RemoveCategory(id int) error

RemoveCategory 从注册表中移除指定ID的类别。

func (*Registry) RemoveView

func (r *Registry) RemoveView(id int) error

RemoveView 从注册表中移除指定ID的视图。

func (*Registry) Size

func (r *Registry) Size() int

Size 获取注册表中CWE弱点条目的数量。

func (*Registry) ViewCount

func (r *Registry) ViewCount() int

ViewCount 获取注册表中视图的数量。

type RelationsResponse

type RelationsResponse struct {
	// Data 包含关系数据的原始JSON
	Data json.RawMessage `json:"Data,omitempty"`
}

RelationsResponse 是关系查询API的响应结构。

type Relationship

type Relationship struct {
	// Nature 关系类型,如ChildOf、ParentOf、CanPrecede等
	Nature RelationshipNature `json:"nature" xml:"Nature,attr"`
	// CWEID 关系目标的CWE ID
	CWEID int `json:"cweId" xml:"CWE_ID"`
	// ViewID 关系所属的视图ID,可选
	ViewID int `json:"viewId,omitempty" xml:"View_ID,omitempty"`
	// Ordinal 关系的序数标记,可选,如"Primary"
	Ordinal string `json:"ordinal,omitempty" xml:"Ordinal,omitempty"`
	// ChainID 关系所属的链ID,可选
	ChainID int `json:"chainId,omitempty" xml:"Chain_ID,omitempty"`
}

Relationship 表示CWE条目之间的关系。

CWE条目之间的关系描述了不同弱点之间的层级、顺序、依赖和对等联系。 关系类型由Nature字段决定,CWEID指定关系的目标弱点。

func NewRelationship

func NewRelationship(nature RelationshipNature, cweID int) *Relationship

NewRelationship 创建一个新的关系。

参数:

  • nature: 关系类型
  • cweID: 目标CWE ID

返回值:

  • *Relationship: 新创建的关系实例

func NewRelationshipWithView

func NewRelationshipWithView(nature RelationshipNature, cweID, viewID int) *Relationship

NewRelationshipWithView 创建一个带有视图ID的新关系。

参数:

  • nature: 关系类型
  • cweID: 目标CWE ID
  • viewID: 所属视图ID

返回值:

  • *Relationship: 新创建的关系实例

func (*Relationship) IsDependency

func (r *Relationship) IsDependency() bool

IsDependency 检查关系是否为依赖关系。

委托给Nature字段的IsDependency方法。 依赖关系包括Requires、RequiredBy。

返回值:

  • bool: 如果是依赖关系返回true,否则返回false

func (*Relationship) IsHierarchical

func (r *Relationship) IsHierarchical() bool

IsHierarchical 检查关系是否为层级关系。

委托给Nature字段的IsHierarchical方法。 层级关系包括ChildOf、ParentOf、MemberOf、HasMember。

返回值:

  • bool: 如果是层级关系返回true,否则返回false

func (*Relationship) IsPeer

func (r *Relationship) IsPeer() bool

IsPeer 检查关系是否为对等关系。

姜托给Nature字段的IsPeer方法。 对等关系包括PeerOf、CanAlsoBe。

返回值:

  • bool: 如果是对等关系返回true,否则返回false

func (*Relationship) IsPrimary

func (r *Relationship) IsPrimary() bool

IsPrimary 检查关系是否标记为主要关系。

当Ordinal字段等于"Primary"时返回true。

返回值:

  • bool: 如果Ordinal为"Primary"返回true,否则返回false

func (*Relationship) IsSequential

func (r *Relationship) IsSequential() bool

IsSequential 检查关系是否为顺序关系。

委托给Nature字段的IsSequential方法。 顺序关系包括CanPrecede、CanFollow。

返回值:

  • bool: 如果是顺序关系返回true,否则返回false

func (*Relationship) Validate

func (r *Relationship) Validate() error

Validate 验证关系的有效性。

检查条件:

  • Nature必须是有效的关系类型
  • CWEID必须大于0

返回值:

  • error: 如果验证失败返回ValidationError,否则返回nil

type RelationshipError

type RelationshipError struct {
	*CWEError
	// From 源CWE ID
	From string
	// To 目标CWE ID
	To string
	// Nature 关系类型
	Nature RelationshipNature
}

RelationshipError 表示关系操作失败的错误。

当尝试建立无效的CWE关系时返回此错误。

func NewRelationshipError

func NewRelationshipError(from, to string, nature RelationshipNature) *RelationshipError

NewRelationshipError 创建一个新的RelationshipError。

参数:

  • from: 源CWE ID
  • to: 目标CWE ID
  • nature: 关系类型

type RelationshipNature

type RelationshipNature string

RelationshipNature 表示CWE条目之间关系的类型。

CWE定义了以下关系类型:

  • ChildOf: 此弱点是目标弱点的子项(更具体)
  • ParentOf: 此弱点是目标弱点的父项(更通用)
  • CanPrecede: 此弱点可以创建使目标弱点成为可能的条件(链式前驱)
  • CanFollow: 此弱点可以跟随目标弱点(链式后继)
  • Requires: 此复合弱点需要目标弱点存在
  • RequiredBy: 此弱点被目标复合弱点所需要
  • CanAlsoBe: 此弱点在适当上下文中也可以被视为目标弱点
  • PeerOf: 与目标弱点有相似性,但不适合其他关系类型
  • MemberOf: 此条目是目标类别/视图的成员
  • HasMember: 此类别/视图包含目标条目作为成员
const (
	RelationshipChildOf    RelationshipNature = "ChildOf"
	RelationshipParentOf   RelationshipNature = "ParentOf"
	RelationshipCanPrecede RelationshipNature = "CanPrecede"
	RelationshipCanFollow  RelationshipNature = "CanFollow"
	RelationshipRequires   RelationshipNature = "Requires"
	RelationshipRequiredBy RelationshipNature = "RequiredBy"
	RelationshipCanAlsoBe  RelationshipNature = "CanAlsoBe"
	RelationshipPeerOf     RelationshipNature = "PeerOf"
	RelationshipMemberOf   RelationshipNature = "MemberOf"
	RelationshipHasMember  RelationshipNature = "Has_Member"
)

func AllRelationshipNatureValues

func AllRelationshipNatureValues() []RelationshipNature

AllRelationshipNatureValues 返回所有有效的关系类型值。

func ParseRelationshipNature

func ParseRelationshipNature(s string) (RelationshipNature, error)

ParseRelationshipNature 从字符串解析关系类型。

func (RelationshipNature) IsDependency

func (r RelationshipNature) IsDependency() bool

IsDependency 检查关系是否为依赖关系(Requires, RequiredBy)。

func (RelationshipNature) IsHierarchical

func (r RelationshipNature) IsHierarchical() bool

IsHierarchical 检查关系是否为层级关系(ChildOf, ParentOf, MemberOf, HasMember)。

func (RelationshipNature) IsPeer

func (r RelationshipNature) IsPeer() bool

IsPeer 检查关系是否为对等关系(PeerOf, CanAlsoBe)。

func (RelationshipNature) IsSequential

func (r RelationshipNature) IsSequential() bool

IsSequential 检查关系是否为顺序关系(CanPrecede, CanFollow)。

func (RelationshipNature) IsValid

func (r RelationshipNature) IsValid() bool

IsValid 检查关系类型是否为有效值。

func (RelationshipNature) String

func (r RelationshipNature) String() string

String 返回关系类型的字符串表示。

type Statistics

type Statistics struct {
	// TotalCount CWE弱点条目总数
	TotalCount int `json:"total_count"`
	// WeaknessCount 弱点数量
	WeaknessCount int `json:"weakness_count"`
	// CategoryCount 类别数量
	CategoryCount int `json:"category_count"`
	// ViewCount 视图数量
	ViewCount int `json:"view_count"`
	// CompoundElementCount 复合元素数量
	CompoundElementCount int `json:"compound_element_count"`
	// ByAbstraction 按抽象层级统计
	ByAbstraction map[Abstraction]int `json:"by_abstraction"`
	// ByStatus 按状态统计
	ByStatus map[Status]int `json:"by_status"`
	// ByStructure 按结构类型统计
	ByStructure map[Structure]int `json:"by_structure"`
	// ByLikelihood 按利用可能性统计
	ByLikelihood map[LikelihoodOfExploit]int `json:"by_likelihood"`
	// TopScopes 影响范围统计(按出现次数排序)
	TopScopes []ConsequenceScopeCount `json:"top_scopes"`
}

Statistics 包含CWE注册表的统计信息。

func ComputeStatistics

func ComputeStatistics(r *Registry) *Statistics

ComputeStatistics 计算CWE注册表的完整统计信息。

参数:

  • r: CWE注册表

返回值:

  • *Statistics: 统计信息

type Status

type Status string

Status 表示CWE条目的状态。

状态值描述了CWE条目的成熟度和稳定性:

  • Stable: 所有重要元素已验证,不太可能发生显著变化
  • Usable: 已经过深入审查,关键元素已验证
  • Draft: 所有重要元素已填写,可能仍有问题或空缺
  • Incomplete: 并非所有重要元素都已填写,无质量保证
  • Obsolete: 仍然有效但不再相关,已被更新的实体取代
  • Deprecated: 已从CWE中移除,是重复或错误创建的
const (
	StatusStable     Status = "Stable"
	StatusUsable     Status = "Usable"
	StatusDraft      Status = "Draft"
	StatusIncomplete Status = "Incomplete"
	StatusObsolete   Status = "Obsolete"
	StatusDeprecated Status = "Deprecated"
)

func AllStatusValues

func AllStatusValues() []Status

AllStatusValues 返回所有有效的状态值。

func ParseStatus

func ParseStatus(s string) (Status, error)

ParseStatus 从字符串解析状态。

func (Status) IsValid

func (s Status) IsValid() bool

IsValid 检查状态是否为有效值。

func (Status) String

func (s Status) String() string

String 返回状态的字符串表示。

type Structure

type Structure string

Structure 表示CWE条目的结构类型。

结构类型描述了弱点之间的组成关系:

  • Simple: 单一弱点,不依赖其他弱点
  • Chain: 链式弱点,多个弱点必须按顺序可达才能产生漏洞
  • Composite: 复合弱点,多个弱点必须同时存在才能产生漏洞
const (
	// StructureSimple 表示简单弱点,不依赖其他弱点的存在
	StructureSimple Structure = "Simple"

	// StructureChain 表示链式弱点,弱点必须按顺序可达
	// 例如:CWE-680 整数溢出到缓冲区溢出
	StructureChain Structure = "Chain"

	// StructureComposite 表示复合弱点,多个弱点必须同时存在
	// 例如:CWE-352 CSRF需要多个弱点同时存在
	StructureComposite Structure = "Composite"
)

func AllStructureValues

func AllStructureValues() []Structure

AllStructureValues 返回所有有效的结构类型值。

func ParseStructure

func ParseStructure(s string) (Structure, error)

ParseStructure 从字符串解析结构类型。

func (Structure) IsValid

func (s Structure) IsValid() bool

IsValid 检查结构类型是否为有效值。

func (Structure) String

func (s Structure) String() string

String 返回结构类型的字符串表示。

type TreeFetcher

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

TreeFetcher 递归获取CWE树结构的获取器。

func NewTreeFetcher

func NewTreeFetcher(client *APIClient, registry *Registry, maxDepth int) *TreeFetcher

NewTreeFetcher 创建一个新的树获取器。

参数:

  • client: API客户端实例
  • registry: 用于存储获取结果的注册表
  • maxDepth: 最大递归深度,0表示无限制

func (*TreeFetcher) FetchFullTree

func (f *TreeFetcher) FetchFullTree(ctx context.Context, rootID int) error

FetchFullTree 获取以指定ID为根的完整CWE树。

该方法同时获取祖先和后代,构建完整的CWE关系树。

func (*TreeFetcher) FetchWithAncestors

func (f *TreeFetcher) FetchWithAncestors(ctx context.Context, id int) error

FetchWithAncestors 获取指定CWE条目及其所有祖先。

该方法递归地获取CWE条目的父级,直到达到根节点或最大深度。

func (*TreeFetcher) FetchWithDescendants

func (f *TreeFetcher) FetchWithDescendants(ctx context.Context, id int) error

FetchWithDescendants 获取指定CWE条目及其所有后代。

该方法递归地获取CWE条目的子级,直到没有子级或达到最大深度。

func (*TreeFetcher) GetRegistry

func (f *TreeFetcher) GetRegistry() *Registry

GetRegistry 获取用于存储结果的注册表。

type TreeNode

type TreeNode struct {
	// CWE 当前节点对应的CWE条目
	CWE *CWE
	// Children 子节点列表
	Children []*TreeNode
	// Parent 父节点
	Parent *TreeNode
	// Depth 节点深度(根节点为0)
	Depth int
}

TreeNode 表示CWE树中的一个节点。

TreeNode包装了CWE条目,添加了树结构信息(父节点、子节点、深度), 用于可视化展示和树形遍历。

func BuildForest

func BuildForest(r *Registry) []*TreeNode

BuildForest 从注册表构建森林(所有顶层Pillar节点的树)。

参数:

  • r: CWE注册表

返回值:

  • []*TreeNode: 所有顶层节点的树列表

func BuildTree

func BuildTree(r *Registry, rootID int) *TreeNode

BuildTree 从注册表构建以指定ID为根的树。

该方法递归地构建CWE条目的树结构。 需要先调用Registry.BuildIndexes构建索引。

参数:

  • r: CWE注册表
  • rootID: 根节点的CWE ID

返回值:

  • *TreeNode: 构建的树根节点,如果根ID不存在返回nil

func BuildViewTree

func BuildViewTree(r *Registry, viewID int) *TreeNode

BuildViewTree 从注册表构建指定视图的树。

参数:

  • r: CWE注册表
  • viewID: 视图ID

返回值:

  • *TreeNode: 视图的根节点树

func NewTreeNode

func NewTreeNode(cwe *CWE) *TreeNode

NewTreeNode 创建一个新的TreeNode。

参数:

  • cwe: 节点对应的CWE条目

返回值:

  • *TreeNode: 新创建的树节点

func (*TreeNode) AddChild

func (n *TreeNode) AddChild(child *TreeNode)

AddChild 向当前节点添加一个子节点。

该方法会自动设置子节点的Parent和Depth。

参数:

  • child: 要添加的子节点

func (*TreeNode) Count

func (n *TreeNode) Count() int

Count 获取当前节点下子树的节点总数(包括自身)。

返回值:

  • int: 节点总数

func (*TreeNode) Find

func (n *TreeNode) Find(id int) *TreeNode

Find 在树中查找指定ID的节点。

参数:

  • id: 要查找的CWE ID

返回值:

  • *TreeNode: 找到的节点,如果未找到返回nil

func (*TreeNode) IsLeaf

func (n *TreeNode) IsLeaf() bool

IsLeaf 检查当前节点是否为叶子节点。

func (*TreeNode) IsRoot

func (n *TreeNode) IsRoot() bool

IsRoot 检查当前节点是否为根节点。

func (*TreeNode) LeafNodes

func (n *TreeNode) LeafNodes() []*TreeNode

LeafNodes 获取当前节点下所有的叶子节点。

返回值:

  • []*TreeNode: 所有叶子节点列表

func (*TreeNode) MaxDepth

func (n *TreeNode) MaxDepth() int

MaxDepth 获取当前节点下子树的最大深度。

返回值:

  • int: 最大深度

func (*TreeNode) Path

func (n *TreeNode) Path() []*TreeNode

Path 返回从根节点到当前节点的路径。

返回值:

  • []*TreeNode: 路径上的节点列表,从根节点到当前节点

func (*TreeNode) String

func (n *TreeNode) String() string

String 返回节点的字符串表示。

func (*TreeNode) Walk

func (n *TreeNode) Walk(fn func(*TreeNode) bool)

Walk 使用深度优先搜索遍历树。

遍历过程中对每个节点调用fn函数。 如果fn返回false,则停止遍历该分支。

参数:

  • fn: 对每个节点调用的函数,返回false停止遍历

func (*TreeNode) WalkBFS

func (n *TreeNode) WalkBFS(fn func(*TreeNode) bool)

WalkBFS 使用广度优先搜索遍历树。

参数:

  • fn: 对每个节点调用的函数,返回false停止遍历

type ValidationError

type ValidationError struct {
	*CWEError
	// Field 验证失败的字段名
	Field string
	// Value 验证失败的值
	Value string
}

ValidationError 表示模型验证失败的错误。

当CWE条目的字段值不符合约束条件时返回此错误。

func NewValidationError

func NewValidationError(field, value string) *ValidationError

NewValidationError 创建一个新的ValidationError。

参数:

  • field: 验证失败的字段名
  • value: 验证失败的值

type VersionResponse

type VersionResponse struct {
	// Version CWE数据版本号
	Version string `json:"version"`
	// ReleaseDate 发布日期
	ReleaseDate string `json:"releaseDate"`
	// Name 版本名称
	Name string `json:"name"`
}

VersionResponse 是版本API的响应结构。

type View

type View struct {
	// ID 视图的数字标识符
	ID int `json:"id" xml:"ID,attr"`
	// Name 视图名称
	Name string `json:"name" xml:"Name"`
	// Type 视图类型(Graph、Explicit Slice、Implicit Slice)
	Type ViewType `json:"type,omitempty" xml:"Type,omitempty"`
	// Status 状态
	Status Status `json:"status,omitempty" xml:"Status,omitempty"`
	// Description 视图描述
	Description string `json:"description" xml:"Description"`
	// Members 视图成员列表
	Members []ViewMember `json:"members,omitempty" xml:"Members>ViewMember,omitempty"`
	// References 参考文献列表
	References []Reference `json:"references,omitempty" xml:"References>Reference,omitempty"`
	// ContentHistory 内容历史
	ContentHistory *ContentHistory `json:"content_history,omitempty" xml:"ContentHistory,omitempty"`
}

View 表示CWE视图条目。

视图是一种CWE条目类型,提供了从特定角度查看和组织弱点的方式。

func NewView

func NewView(id int, name string, viewType ViewType) *View

NewView 创建一个新的CWE视图条目。

参数:

  • id: 视图的数字标识符
  • name: 视图名称
  • viewType: 视图类型

返回值:

  • *View: 新创建的视图实例

type ViewMember

type ViewMember struct {
	// CWEID 成员的CWE ID
	CWEID int `json:"cwe_id" xml:"CWE_ID"`
	// ViewID 所属视图ID
	ViewID int `json:"view_id" xml:"View_ID"`
	// Direct 是否为直接成员
	Direct bool `json:"direct" xml:"Direct"`
	// Predicate 谓词,可选
	Predicate string `json:"predicate,omitempty" xml:"Predicate,omitempty"`
}

ViewMember 表示视图成员。

视图成员描述了某个CWE条目在特定视图中的归属关系。

type ViewType

type ViewType string

ViewType 表示CWE视图的类型。

const (
	// ViewTypeGraph 表示图类型视图,具有层次化的关系表示
	// 例如:CWE-1000 研究概念,CWE-699 软件开发
	ViewTypeGraph ViewType = "Graph"

	// ViewTypeExplicitSlice 表示显式切片视图,通过外部因素相关的扁平列表
	// 例如:CWE Top 25, OWASP Top Ten
	ViewTypeExplicitSlice ViewType = "Explicit Slice"

	// ViewTypeImplicitSlice 表示隐式切片视图,通过过滤器/属性定义的扁平列表
	// 例如:所有草稿状态的条目
	ViewTypeImplicitSlice ViewType = "Implicit Slice"
)

func AllViewTypeValues

func AllViewTypeValues() []ViewType

AllViewTypeValues 返回所有有效的视图类型值。

func ParseViewType

func ParseViewType(s string) (ViewType, error)

ParseViewType 从字符串解析视图类型。

func (ViewType) IsValid

func (v ViewType) IsValid() bool

IsValid 检查视图类型是否为有效值。

func (ViewType) String

func (v ViewType) String() string

String 返回视图类型的字符串表示。

type ViewsResponse

type ViewsResponse struct {
	// Data 包含视图数据的原始JSON
	Data json.RawMessage `json:"Data,omitempty"`
	// Views 视图列表
	Views []View `json:"views,omitempty"`
}

ViewsResponse 是视图查询API的响应结构。

type WeaknessesResponse

type WeaknessesResponse struct {
	// Data 包含弱点数据的原始JSON
	Data json.RawMessage `json:"Data"`
	// Weaknesses 弱点列表
	Weaknesses []CWE `json:"weaknesses,omitempty"`
}

WeaknessesResponse 是弱点查询API的响应结构。

type XMLParser

type XMLParser struct{}

XMLParser 解析MITRE CWE XML目录格式。

该解析器支持解析MITRE官方提供的CWE XML下载文件, 将XML数据转换为Registry中的CWE条目。 这是实现离线模式的关键组件。

支持的XML格式为MITRE CWE Schema 7.x版本。

示例:

parser := cwe.NewXMLParser()
registry, err := parser.ParseFile("cwec_v4.10.xml")
if err != nil {
    log.Fatal(err)
}

func NewXMLParser

func NewXMLParser() *XMLParser

NewXMLParser 创建一个新的XML解析器。

func (*XMLParser) Parse

func (p *XMLParser) Parse(reader io.Reader) (*Registry, error)

Parse 从io.Reader解析CWE XML目录。

参数:

  • reader: 包含XML数据的io.Reader

返回值:

  • *Registry: 解析后的CWE注册表
  • error: 解析失败时返回错误

func (*XMLParser) ParseBytes

func (p *XMLParser) ParseBytes(data []byte) (*Registry, error)

ParseBytes 从字节数组解析CWE XML目录。

参数:

  • data: XML数据的字节数组

返回值:

  • *Registry: 解析后的CWE注册表
  • error: 解析失败时返回错误

func (*XMLParser) ParseFile

func (p *XMLParser) ParseFile(path string) (*Registry, error)

ParseFile 从文件解析CWE XML目录。

参数:

  • path: XML文件路径

返回值:

  • *Registry: 解析后的CWE注册表
  • error: 解析失败时返回错误

Directories

Path Synopsis
cmd
cwe command
cwe-mcp command
Package main 是 CWE Skills 的 MCP (Model Context Protocol) 服务器。
Package main 是 CWE Skills 的 MCP (Model Context Protocol) 服务器。

Jump to

Keyboard shortcuts

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