1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
package feed
import (
"encoding/json"
"fmt"
"regexp"
"strconv"
)
// CVE ID
type CveId uint32
var cveIdRe = regexp.MustCompile("\\ACVE-(\\d{4})-(\\d{1,8})\\z")
// parse year component of CVE ID
func parseCveIdYear(s string) (uint16, error) {
// parse year, check for error
year, err := strconv.ParseUint(s, 10, 16)
if err != nil {
return 0, err
}
// check bounds
if year < 1999 || year > 2126 {
return 0, fmt.Errorf("year out of bounds: %s", s)
}
// return value
return uint16(year), nil
}
// parse number component of CVE ID
func parseCveIdNum(s string) (uint32, error) {
// parse number, check for error
num, err := strconv.ParseUint(s, 10, 32)
if err != nil {
return 0, err
}
// check bounds
if num > 0x01ffffff {
return 0, fmt.Errorf("number out of bounds: %d", num)
}
// return value
return uint32(num), nil
}
// Encode CVE ID as uint32.
func encodeCveId(year uint16, num uint32) uint32 {
return uint32((uint32((year - 1999) & 0x7f) << 25) | (num & 0x01ffffff))
}
// Create CVE ID from string.
func NewCveId(s string) (CveId, error) {
// match components, check for error
md := cveIdRe.FindStringSubmatch(s)
if len(md) != 3 {
return CveId(0), fmt.Errorf("invalid CVE ID: %s", s)
}
// parse year, check for error
year, err := parseCveIdYear(md[1])
if err != nil {
return CveId(0), err
}
// parse number, check for error
num, err := parseCveIdNum(md[2])
if err != nil {
return CveId(0), err
}
// encode and return result
return CveId(encodeCveId(year, num)), nil
}
// Unmarshal CVE ID from JSON.
func (me *CveId) UnmarshalJSON(b []byte) error {
// decode string, check for error
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
// parse year, check for error
r, err := NewCveId(s)
if err != nil {
return err
}
// serialize ID
*me = r
// return success
return nil
}
// Get year component.
func (me CveId) Year() uint16 {
return uint16((uint32(me) >> 25) & 0x7f) + 1999
}
// Get number component.
func (me CveId) Number() uint32 {
return (uint32(me) & 0x01ffffff)
}
// Return string representation of CVE ID.
func (me CveId) String() string {
return fmt.Sprintf("CVE-%04d-%04d", me.Year(), me.Number())
}
|