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
- Variables
- func CompareCWEIDs(a, b string) (int, error)
- func CountByAbstraction(r *Registry, a Abstraction) int
- func CountByLikelihood(r *Registry, l LikelihoodOfExploit) int
- func CountByScope(r *Registry, scope ConsequenceScope) int
- func CountByStatus(r *Registry, s Status) int
- func ExtractCWEIDs(text string) []string
- func ExtractFirstCWEID(text string) string
- func FormatCWEID(id string) (string, error)
- func FormatCWEIDFromInt(id int) string
- func GetOWASPCategories(cweID int) []string
- func GetOWASPCategory(cweID int) string
- func GroupByAbstraction(cwes []*CWE) map[Abstraction][]*CWE
- func GroupByLikelihood(cwes []*CWE) map[LikelihoodOfExploit][]*CWE
- func GroupByStatus(cwes []*CWE) map[Status][]*CWE
- func IsCWEID(text string) bool
- func IsInOWASPTop10(cweID int) bool
- func IsInSANSTop25(cweID int) bool
- func IsInTop25(cweID int) bool
- func IsInWellKnownView(viewID int) bool
- func MarshalCSV(cwes []*CWE) ([]byte, error)
- func MarshalJSON(cwe *CWE) ([]byte, error)
- func MarshalJSONList(cwes []*CWE) ([]byte, error)
- func MarshalXML(cwe *CWE) ([]byte, error)
- func ParseCWEID(id string) (int, error)
- func ValidateCWEID(text string) error
- type APIClient
- func (c *APIClient) Close()
- func (c *APIClient) GetAncestors(ctx context.Context, id int) ([]Relationship, error)
- func (c *APIClient) GetBaseURL() string
- func (c *APIClient) GetCWEs(ctx context.Context, ids []int) (map[string]*CWE, error)
- func (c *APIClient) GetCategory(ctx context.Context, id int) (*Category, error)
- func (c *APIClient) GetChildren(ctx context.Context, id int, viewID ...int) ([]Relationship, error)
- func (c *APIClient) GetDescendants(ctx context.Context, id int) ([]Relationship, error)
- func (c *APIClient) GetHTTPClient() *HTTPClient
- func (c *APIClient) GetParents(ctx context.Context, id int, viewID ...int) ([]Relationship, error)
- func (c *APIClient) GetRateLimiter() *RateLimiter
- func (c *APIClient) GetVersion(ctx context.Context) (*VersionResponse, error)
- func (c *APIClient) GetView(ctx context.Context, id int) (*View, error)
- func (c *APIClient) GetWeakness(ctx context.Context, id int) (*CWE, error)
- func (c *APIClient) SetBaseURL(url string)
- func (c *APIClient) SetHTTPClient(client *HTTPClient)
- func (c *APIClient) SetRateLimiter(limiter *RateLimiter)
- type APIClientOption
- func WithAPIBaseURL(url string) APIClientOption
- func WithAPIHTTPClient(opts ...HTTPClientOption) APIClientOption
- func WithAPIRateLimit(rate float64, burst int) APIClientOption
- func WithAPIRetry(maxRetries int, delay time.Duration) APIClientOption
- func WithAPITimeout(timeout time.Duration) APIClientOption
- type APIError
- type APIResponse
- type Abstraction
- type AlternateTerm
- type ApplicablePlatforms
- type BasicFetcher
- func (f *BasicFetcher) Fetch(ctx context.Context, id int) (*CWE, error)
- func (f *BasicFetcher) FetchCategory(ctx context.Context, id int) (*Category, error)
- func (f *BasicFetcher) FetchView(ctx context.Context, id int) (*View, error)
- func (f *BasicFetcher) FetchWithRelations(ctx context.Context, id int, viewID ...int) (*CWE, error)
- type CWE
- func Deduplicate(cwes []*CWE) []*CWE
- func Filter(cwes []*CWE, opts ...FilterOption) []*CWE
- func FindBaseWeaknesses(r *Registry) []*CWE
- func FindByAbstraction(r *Registry, abstraction Abstraction) []*CWE
- func FindByConsequenceScope(r *Registry, scope ConsequenceScope) []*CWE
- func FindByID(r *Registry, id int) (*CWE, bool)
- func FindByKeyword(r *Registry, keyword string) []*CWE
- func FindByLikelihood(r *Registry, likelihood LikelihoodOfExploit) []*CWE
- func FindByStatus(r *Registry, status Status) []*CWE
- func FindByStructure(r *Registry, structure Structure) []*CWE
- func FindChains(r *Registry) []*CWE
- func FindComposites(r *Registry) []*CWE
- func FindTopLevel(r *Registry) []*CWE
- func NewCWE(id int, name string) *CWE
- func SortByAbstraction(cwes []*CWE) []*CWE
- func SortByID(cwes []*CWE) []*CWE
- func SortByName(cwes []*CWE) []*CWE
- func UnmarshalCSV(data []byte) ([]*CWE, error)
- func UnmarshalJSON(data []byte) (*CWE, error)
- func UnmarshalJSONList(data []byte) ([]*CWE, error)
- func UnmarshalXML(data []byte) (*CWE, error)
- func (c *CWE) CWEID() string
- func (c *CWE) GetChainIDs() []int
- func (c *CWE) GetChildIDs() []int
- func (c *CWE) GetParentIDs() []int
- func (c *CWE) GetPeerIDs() []int
- func (c *CWE) HasConsequenceScope(scope ConsequenceScope) bool
- func (c *CWE) IsBase() bool
- func (c *CWE) IsCategory() bool
- func (c *CWE) IsChain() bool
- func (c *CWE) IsComposite() bool
- func (c *CWE) IsCompoundElement() bool
- func (c *CWE) IsDeprecated() bool
- func (c *CWE) IsPillar() bool
- func (c *CWE) IsStable() bool
- func (c *CWE) IsVariant() bool
- func (c *CWE) IsView() bool
- func (c *CWE) IsWeakness() bool
- func (c *CWE) Validate() error
- type CWEError
- type CWENotFoundError
- type CWEsResponse
- type CategoriesResponse
- type Category
- type CompoundElement
- type Consequence
- type ConsequenceImpact
- type ConsequenceScope
- type ConsequenceScopeCount
- type ContentHistory
- type DataFetcher
- type DemonstrativeExample
- type Effectiveness
- type FilterOption
- type HTTPClient
- func (c *HTTPClient) Close()
- func (c *HTTPClient) Get(ctx context.Context, path string, result interface{}) error
- func (c *HTTPClient) GetBaseURL() string
- func (c *HTTPClient) GetHTTPClient() *http.Client
- func (c *HTTPClient) GetMaxRetries() int
- func (c *HTTPClient) GetRateLimiter() *RateLimiter
- func (c *HTTPClient) GetRaw(ctx context.Context, path string) ([]byte, error)
- func (c *HTTPClient) GetRetryDelay() time.Duration
- func (c *HTTPClient) Post(ctx context.Context, path string, body interface{}, result interface{}) error
- func (c *HTTPClient) PostForm(ctx context.Context, path string, data url.Values, result interface{}) error
- func (c *HTTPClient) SetBaseURL(url string)
- func (c *HTTPClient) SetHTTPClient(client *http.Client)
- func (c *HTTPClient) SetMaxRetries(maxRetries int)
- func (c *HTTPClient) SetRateLimiter(limiter *RateLimiter)
- func (c *HTTPClient) SetRetryDelay(delay time.Duration)
- type HTTPClientOption
- func WithHTTPClient(client *http.Client) HTTPClientOption
- func WithHTTPRateLimiter(rate float64, burst int) HTTPClientOption
- func WithHTTPTimeout(timeout time.Duration) HTTPClientOption
- func WithRetry(maxRetries int, delay time.Duration) HTTPClientOption
- func WithUserAgent(ua string) HTTPClientOption
- type HistoryEntry
- type Introduction
- type IntroductionPhase
- type InvalidCWEIDError
- type LikelihoodOfExploit
- type Mitigation
- type MitigationPhase
- type MultipleFetcher
- type Navigator
- func (n *Navigator) Ancestors(id int) []*CWE
- func (n *Navigator) CanAlsoBe(id int) []*CWE
- func (n *Navigator) CanFollow(id int) []*CWE
- func (n *Navigator) CanPrecede(id int) []*CWE
- func (n *Navigator) ChainMembers(id int) []*CWE
- func (n *Navigator) Children(id int) []*CWE
- func (n *Navigator) CompositeMembers(id int) []*CWE
- func (n *Navigator) Descendants(id int) []*CWE
- func (n *Navigator) IsAncestorOf(ancestor, descendant int) bool
- func (n *Navigator) IsDescendantOf(descendant, ancestor int) bool
- func (n *Navigator) IsRelated(a, b int) bool
- func (n *Navigator) Parents(id int) []*CWE
- func (n *Navigator) Peers(id int) []*CWE
- func (n *Navigator) RelationshipDepth(ancestor, descendant int) int
- func (n *Navigator) RequiredBy(id int) []*CWE
- func (n *Navigator) Requires(id int) []*CWE
- func (n *Navigator) ShortestPath(from, to int) []int
- func (n *Navigator) Siblings(id int) []*CWE
- func (n *Navigator) String() string
- type ObservedExample
- type ParseError
- type PlatformEntry
- type PlatformType
- type Prevalence
- type RateLimitError
- type RateLimiter
- func (r *RateLimiter) Allow() bool
- func (r *RateLimiter) GetBurst() int
- func (r *RateLimiter) GetInterval() time.Duration
- func (r *RateLimiter) GetRate() float64
- func (r *RateLimiter) ResetLastRequest()
- func (r *RateLimiter) SetInterval(interval time.Duration)
- func (r *RateLimiter) Tokens() float64
- func (r *RateLimiter) Wait(ctx context.Context) error
- func (r *RateLimiter) WaitForRequest()
- type Reference
- type Registry
- func (r *Registry) BuildIndexes()
- func (r *Registry) CategoryCount() int
- func (r *Registry) Clear()
- func (r *Registry) CompoundElementCount() int
- func (r *Registry) Contains(id int) bool
- func (r *Registry) ExportCSV() ([]byte, error)
- func (r *Registry) ExportJSON() ([]byte, error)
- func (r *Registry) Get(id int) (*CWE, bool)
- func (r *Registry) GetAll() []*CWE
- func (r *Registry) GetAllCategories() []*Category
- func (r *Registry) GetAllViews() []*View
- func (r *Registry) GetAncestorIDs(id int) []int
- func (r *Registry) GetCategory(id int) (*Category, bool)
- func (r *Registry) GetCategoryMembers(categoryID int) []int
- func (r *Registry) GetChildIDs(id int) []int
- func (r *Registry) GetCompoundElement(id int) (*CompoundElement, bool)
- func (r *Registry) GetDescendantIDs(id int) []int
- func (r *Registry) GetMemberOfIDs(id int) []int
- func (r *Registry) GetParentIDs(id int) []int
- func (r *Registry) GetPeerIDs(id int) []int
- func (r *Registry) GetView(id int) (*View, bool)
- func (r *Registry) GetViewMembers(viewID int) []int
- func (r *Registry) ImportJSON(jsonData []byte) error
- func (r *Registry) IndexesBuilt() bool
- func (r *Registry) Register(cwe *CWE) error
- func (r *Registry) RegisterCategory(cat *Category) error
- func (r *Registry) RegisterCompoundElement(ce *CompoundElement) error
- func (r *Registry) RegisterView(view *View) error
- func (r *Registry) Remove(id int) error
- func (r *Registry) RemoveCategory(id int) error
- func (r *Registry) RemoveView(id int) error
- func (r *Registry) Size() int
- func (r *Registry) ViewCount() int
- type RelationsResponse
- type Relationship
- type RelationshipError
- type RelationshipNature
- type Statistics
- type Status
- type Structure
- type TreeFetcher
- type TreeNode
- func (n *TreeNode) AddChild(child *TreeNode)
- func (n *TreeNode) Count() int
- func (n *TreeNode) Find(id int) *TreeNode
- func (n *TreeNode) IsLeaf() bool
- func (n *TreeNode) IsRoot() bool
- func (n *TreeNode) LeafNodes() []*TreeNode
- func (n *TreeNode) MaxDepth() int
- func (n *TreeNode) Path() []*TreeNode
- func (n *TreeNode) String() string
- func (n *TreeNode) Walk(fn func(*TreeNode) bool)
- func (n *TreeNode) WalkBFS(fn func(*TreeNode) bool)
- type ValidationError
- type VersionResponse
- type View
- type ViewMember
- type ViewType
- type ViewsResponse
- type WeaknessesResponse
- type XMLParser
Constants ¶
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常量
const DefaultBaseURL = "https://cwe-api.mitre.org/api/v1"
DefaultBaseURL 是MITRE CWE REST API的默认基础URL
const DefaultTimeout = 30 * time.Second
DefaultTimeout 是HTTP请求的默认超时时间
const DefaultUserAgent = "cwe-sdk-go/" + Version
DefaultUserAgent 是HTTP请求的默认User-Agent
const Version = "v0.0.1"
Version 表示本SDK的版本号
Variables ¶
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评分计算得出, 代表了对软件最严重的安全威胁。
使用场景:
- 安全工具优先级排序
- 开发者安全培训重点
- 漏洞管理风险评估
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应用安全评估
- 合规性检查
- 安全测试用例设计
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 ¶
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 ExtractCWEIDs ¶
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 ¶
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 ¶
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 ¶
FormatCWEIDFromInt 将整数ID格式化为标准CWE ID字符串 "CWE-NNN"。
参数:
- id: 整数形式的CWE ID
返回值:
- string: 格式化后的标准CWE ID字符串
示例:
FormatCWEIDFromInt(79) // 返回 "CWE-79" FormatCWEIDFromInt(1000) // 返回 "CWE-1000"
func GetOWASPCategories ¶
GetOWASPCategories 获取给定CWE ID所属的所有OWASP Top 10类别。
与GetOWASPCategory不同,该函数返回所有匹配的类别。
参数:
- cweID: 需要查询的CWE ID数字
返回值:
- []string: 所有匹配的OWASP类别名称列表,如果没有匹配返回空切片
func GetOWASPCategory ¶
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 IsCWEID ¶
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 ¶
IsInOWASPTop10 检查给定的CWE ID是否在OWASP Top 10映射中。
参数:
- cweID: 需要检查的CWE ID数字
返回值:
- bool: 如果在OWASP Top 10中返回true,否则返回false
func IsInSANSTop25 ¶
IsInSANSTop25 检查给定的CWE ID是否在SANS Top 25列表中。
参数:
- cweID: 需要检查的CWE ID数字
返回值:
- bool: 如果在SANS Top 25中返回true,否则返回false
func IsInTop25 ¶
IsInTop25 检查给定的CWE ID是否在CWE Top 25列表中。
参数:
- cweID: 需要检查的CWE ID数字
返回值:
- bool: 如果在Top 25中返回true,否则返回false
func IsInWellKnownView ¶
IsInWellKnownView 检查给定的视图ID是否为知名视图。
知名视图包括:CWE-1000(研究概念)、CWE-699(软件开发)、 CWE-1199(硬件设计)、CWE-888(横截面)、CWE-1400(综合字典)。
参数:
- viewID: 需要检查的视图ID数字
返回值:
- bool: 如果是知名视图返回true,否则返回false
func MarshalJSON ¶
MarshalJSON 将CWE条目序列化为JSON格式。
参数:
- cwe: 要序列化的CWE条目
返回值:
- []byte: JSON数据
- error: 序列化失败时返回错误
func MarshalJSONList ¶
MarshalJSONList 将CWE条目列表序列化为JSON格式。
func ParseCWEID ¶
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 ¶
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) GetAncestors ¶
GetAncestors 获取指定CWE条目的所有祖先关系。
该方法调用 MITRE CWE REST API 的 GET /cwe/{id}/ancestors 端点, 返回此CWE条目的所有祖先(递归的父级)关系。
参数:
- ctx: 请求上下文
- id: CWE ID数字
返回值:
- []Relationship: 祖先关系列表
- error: 请求失败时返回错误
func (*APIClient) GetCWEs ¶
GetCWEs 批量获取多个CWE弱点。
该方法调用 MITRE CWE REST API 的 GET /cwe/{ids} 端点, 可以一次获取多个CWE弱点的信息。
参数:
- ctx: 请求上下文
- ids: CWE ID数字列表
返回值:
- map[string]*CWE: 以CWE ID字符串为键的弱点映射
- error: 请求失败时返回错误
func (*APIClient) GetCategory ¶
GetCategory 获取指定ID的CWE类别详情。
该方法调用 MITRE CWE REST API 的 GET /cwe/category/{id} 端点。
参数:
- ctx: 请求上下文
- id: 类别ID数字
返回值:
- *Category: 类别详情
- error: 请求失败时返回错误
func (*APIClient) GetChildren ¶
GetChildren 获取指定CWE条目的子级关系。
该方法调用 MITRE CWE REST API 的 GET /cwe/{id}/children 端点, 返回在指定视图中此CWE条目的所有子级关系。
参数:
- ctx: 请求上下文
- id: CWE ID数字
- viewID: 可选的视图ID,用于限定关系范围
返回值:
- []Relationship: 子级关系列表
- error: 请求失败时返回错误
func (*APIClient) GetDescendants ¶
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 ¶
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 ¶
GetView 获取指定ID的CWE视图详情。
该方法调用 MITRE CWE REST API 的 GET /cwe/view/{id} 端点。
参数:
- ctx: 请求上下文
- id: 视图ID数字,例如 1000
返回值:
- *View: 视图详情
- error: 请求失败时返回错误
func (*APIClient) GetWeakness ¶
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) 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。
参数:
- url: 基础URL,默认为 "https://cwe-api.mitre.org/api/v1"
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的请求返回错误状态码时返回此错误。
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
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) FetchCategory ¶
FetchCategory 通过API获取指定ID的CWE类别。
func (*BasicFetcher) FetchWithRelations ¶
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 Filter ¶
func Filter(cwes []*CWE, opts ...FilterOption) []*CWE
Filter 根据过滤选项过滤CWE条目列表。
所有非零值的选项都会作为过滤条件,条件之间是AND关系。 零值的选项被忽略。
参数:
- cwes: 要过滤的CWE条目列表
- opts: 过滤选项(可以指定多个,但只使用第一个)
返回值:
- []*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 ¶
FindByID 在注册表中根据ID查找CWE弱点条目。
参数:
- r: CWE注册表
- id: 要查找的CWE ID
返回值:
- *CWE: 找到的CWE条目,如果未找到返回nil
- bool: 是否找到
func FindByKeyword ¶
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 ¶
FindByStatus 在注册表中查找指定状态的所有CWE条目。
参数:
- r: CWE注册表
- status: CWE状态
返回值:
- []*CWE: 匹配的CWE条目列表
func FindByStructure ¶
FindByStructure 在注册表中查找指定结构类型的所有CWE条目。
参数:
- r: CWE注册表
- structure: 结构类型
返回值:
- []*CWE: 匹配的CWE条目列表
func NewCWE ¶
NewCWE 创建一个新的CWE弱点条目。
创建的CWE条目默认CWEType为"weakness"。
参数:
- id: CWE条目的数字标识符
- name: CWE条目的名称
返回值:
- *CWE: 新创建的CWE实例
func UnmarshalJSON ¶
UnmarshalJSON 从JSON数据反序列化CWE条目。
参数:
- data: JSON数据
返回值:
- *CWE: 反序列化的CWE条目
- error: 反序列化失败时返回错误
func UnmarshalJSONList ¶
UnmarshalJSONList 从JSON数据反序列化CWE条目列表。
func (*CWE) GetChainIDs ¶
GetChainIDs 获取与此弱点相关的链式CWE ID。
通过遍历Relationships中Nature为CanPrecede或CanFollow的关系来获取链式ID。
返回值:
- []int: 链式CWE ID列表
func (*CWE) GetChildIDs ¶
GetChildIDs 获取此弱点的所有子级CWE ID。
通过遍历Relationships中Nature为ParentOf的关系来获取子级ID。
返回值:
- []int: 子级CWE ID列表
func (*CWE) GetParentIDs ¶
GetParentIDs 获取此弱点的所有父级CWE ID。
通过遍历Relationships中Nature为ChildOf的关系来获取父级ID。
返回值:
- []int: 父级CWE ID列表
func (*CWE) GetPeerIDs ¶
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 ¶
IsBase 检查CWE条目是否为基础级别。
返回值:
- bool: 如果Abstraction为AbstractionBase返回true,否则返回false
func (*CWE) IsComposite ¶
IsComposite 检查CWE条目是否为复合结构。
返回值:
- bool: 如果Structure为StructureComposite返回true,否则返回false
func (*CWE) IsCompoundElement ¶
IsCompoundElement 检查CWE条目是否为复合元素类型。
返回值:
- bool: 如果CWEType为"compound_element"返回true,否则返回false
func (*CWE) IsDeprecated ¶
IsDeprecated 检查CWE条目是否已废弃。
返回值:
- bool: 如果Status为StatusDeprecated返回true,否则返回false
func (*CWE) IsPillar ¶
IsPillar 检查CWE条目是否为柱石级别。
返回值:
- bool: 如果Abstraction为AbstractionPillar返回true,否则返回false
func (*CWE) IsVariant ¶
IsVariant 检查CWE条目是否为变体级别。
返回值:
- bool: 如果Abstraction为AbstractionVariant返回true,否则返回false
type CWEError ¶
type CWEError struct {
// Code 错误码
Code string
// Message 错误消息
Message string
// Detail 详细信息
Detail string
// Err 被包装的内部错误
Err error
}
CWEError 是所有CWE SDK错误的基础类型。
该类型提供了统一的错误结构,包含错误码、消息和详细信息, 方便上层应用进行错误分类和处理。
type CWENotFoundError ¶
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条目类型,用于将相关的弱点分组归类。
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 检查影响严重程度是否为有效值。
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 从字符串解析影响范围。
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 从字符串解析有效性。
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) 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) GetHTTPClient ¶
func (c *HTTPClient) GetHTTPClient() *http.Client
GetHTTPClient 获取底层的http.Client。
func (*HTTPClient) GetRateLimiter ¶
func (c *HTTPClient) GetRateLimiter() *RateLimiter
GetRateLimiter 获取速率限制器。
func (*HTTPClient) GetRaw ¶
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) 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 从字符串解析引入阶段。
type InvalidCWEIDError ¶
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 从字符串解析缓解措施阶段。
type MultipleFetcher ¶
type MultipleFetcher struct {
// contains filtered or unexported fields
}
MultipleFetcher 批量获取CWE条目的获取器。
func NewMultipleFetcher ¶
func NewMultipleFetcher(client *APIClient) *MultipleFetcher
NewMultipleFetcher 创建一个新的批量获取器。
func (*MultipleFetcher) FetchMultiple ¶
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 ¶
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 (*Navigator) CanPrecede ¶
CanPrecede 获取指定CWE条目可以前置的条目(链式前驱)。
func (*Navigator) ChainMembers ¶
ChainMembers 获取指定链式复合元素的所有链成员。
func (*Navigator) CompositeMembers ¶
CompositeMembers 获取指定复合元素的所有组合成员。
func (*Navigator) Descendants ¶
Descendants 递归获取指定CWE条目的所有后代条目。
func (*Navigator) IsAncestorOf ¶
IsAncestorOf 检查ancestor是否是descendant的祖先。
func (*Navigator) IsDescendantOf ¶
IsDescendantOf 检查descendant是否是ancestor的后代。
func (*Navigator) RelationshipDepth ¶
RelationshipDepth 计算两个CWE条目之间的层级关系深度。
如果两者不存在层级关系,返回-1。 直接的父子关系深度为1。
func (*Navigator) RequiredBy ¶
RequiredBy 获取需要指定CWE条目的条目。
func (*Navigator) ShortestPath ¶
ShortestPath 查找两个CWE条目之间的最短路径。
使用广度优先搜索在关系图中查找从from到to的最短路径。 返回的路径包含起点和终点。
参数:
- from: 起始CWE ID
- to: 目标CWE ID
返回值:
- []int: 路径上的CWE ID列表,如果不存在路径返回nil
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 ¶
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 从字符串解析平台类型。
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 从字符串解析普遍程度。
type RateLimitError ¶
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 (*Registry) BuildIndexes ¶
func (r *Registry) BuildIndexes()
BuildIndexes 构建关系索引。
该方法遍历所有CWE条目的关系数据,构建以下索引:
- 父子关系索引(基于ChildOf/ParentOf关系)
- 对等关系索引(基于PeerOf/CanAlsoBe关系)
- 成员关系索引(基于类别/视图的成员列表)
构建索引后,GetParentIDs、GetChildIDs、GetAncestorIDs等方法 可以快速返回结果。建议在数据加载完成后调用此方法。
func (*Registry) CompoundElementCount ¶
CompoundElementCount 获取注册表中复合元素的数量。
func (*Registry) ExportJSON ¶
ExportJSON 将注册表数据导出为JSON格式。
func (*Registry) GetAllCategories ¶
GetAllCategories 获取所有CWE类别。
func (*Registry) GetAncestorIDs ¶
GetAncestorIDs 递归获取指定CWE条目的所有祖先ID。
需要先调用BuildIndexes构建索引。 该方法使用广度优先搜索遍历父级关系,避免循环引用导致的无限递归。
func (*Registry) GetCategory ¶
GetCategory 根据ID获取CWE类别。
func (*Registry) GetCategoryMembers ¶
GetCategoryMembers 获取指定类别的成员ID列表。
func (*Registry) GetCompoundElement ¶
func (r *Registry) GetCompoundElement(id int) (*CompoundElement, bool)
GetCompoundElement 根据ID获取复合元素。
func (*Registry) GetDescendantIDs ¶
GetDescendantIDs 递归获取指定CWE条目的所有后代ID。
需要先调用BuildIndexes构建索引。 该方法使用广度优先搜索遍历子级关系,避免循环引用导致的无限递归。
func (*Registry) GetMemberOfIDs ¶
GetMemberOfIDs 获取指定CWE条目所属的类别/视图ID列表。
func (*Registry) GetViewMembers ¶
GetViewMembers 获取指定视图的成员ID列表。
func (*Registry) ImportJSON ¶
ImportJSON 从JSON格式导入数据到注册表。
func (*Registry) Register ¶
Register 向注册表中注册一个CWE弱点条目。
如果ID已存在,返回ValidationError。
参数:
- cwe: 要注册的CWE条目
返回值:
- error: 注册失败时返回错误
func (*Registry) RegisterCategory ¶
RegisterCategory 向注册表中注册一个CWE类别。
func (*Registry) RegisterCompoundElement ¶
func (r *Registry) RegisterCompoundElement(ce *CompoundElement) error
RegisterCompoundElement 向注册表中注册一个复合元素。
func (*Registry) RegisterView ¶
RegisterView 向注册表中注册一个CWE视图。
func (*Registry) RemoveCategory ¶
RemoveCategory 从注册表中移除指定ID的类别。
func (*Registry) RemoveView ¶
RemoveView 从注册表中移除指定ID的视图。
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 检查关系类型是否为有效值。
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中移除,是重复或错误创建的
type Structure ¶
type Structure string
Structure 表示CWE条目的结构类型。
结构类型描述了弱点之间的组成关系:
- Simple: 单一弱点,不依赖其他弱点
- Chain: 链式弱点,多个弱点必须按顺序可达才能产生漏洞
- Composite: 复合弱点,多个弱点必须同时存在才能产生漏洞
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 BuildTree ¶
BuildTree 从注册表构建以指定ID为根的树。
该方法递归地构建CWE条目的树结构。 需要先调用Registry.BuildIndexes构建索引。
参数:
- r: CWE注册表
- rootID: 根节点的CWE ID
返回值:
- *TreeNode: 构建的树根节点,如果根ID不存在返回nil
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条目类型,提供了从特定角度查看和组织弱点的方式。
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" )
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 (*XMLParser) Parse ¶
Parse 从io.Reader解析CWE XML目录。
参数:
- reader: 包含XML数据的io.Reader
返回值:
- *Registry: 解析后的CWE注册表
- error: 解析失败时返回错误
func (*XMLParser) ParseBytes ¶
ParseBytes 从字节数组解析CWE XML目录。
参数:
- data: XML数据的字节数组
返回值:
- *Registry: 解析后的CWE注册表
- error: 解析失败时返回错误
Source Files
¶
- api_client.go
- api_client_cwe.go
- api_client_relations.go
- api_client_version.go
- api_response.go
- consequences.go
- cwe.go
- cwe_utils.go
- data_fetcher.go
- enums.go
- errors.go
- filter.go
- http_client.go
- http_rate_limiter.go
- model.go
- navigator.go
- registry.go
- relationship.go
- search.go
- serializer.go
- stats.go
- tree.go
- wellknown_ids.go
- xml_parser.go