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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! CPE parsing and NVD observation extraction.
//!
//! Both CPE 2.3 formatted strings and CPE 2.2 URIs are parsed into their full
//! component sets. [`observations_from_cve`] walks NVD `configurations` and
//! `affected` blocks and returns one observation per affected entry and one
//! per CPE criteria, deduplicated deterministically.
use std::collections::BTreeSet;
use percent_encoding::percent_decode_str;
use serde_json::Value;
use super::{ObservedProduct, VersionRange};
/// A parsed CPE name with every bound component.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Cpe {
/// Original input string.
pub raw: String,
pub part: Option<String>,
pub vendor: Option<String>,
pub product: Option<String>,
pub version: Option<String>,
pub update: Option<String>,
pub edition: Option<String>,
pub language: Option<String>,
pub sw_edition: Option<String>,
pub target_sw: Option<String>,
pub target_hw: Option<String>,
pub target_os: Option<String>,
pub other: Option<String>,
}
impl Cpe {
/// Build a versionless observation carrying this CPE as its only alias.
pub fn to_observed(&self, source: impl Into<String>) -> ObservedProduct {
ObservedProduct {
source: source.into(),
part: self.part.clone(),
vendor: self.vendor.clone().unwrap_or_default(),
product: self.product.clone().unwrap_or_default(),
version: self.version.clone(),
update: self.update.clone(),
edition: self.edition.clone(),
target_sw: self.target_sw.clone(),
target_hw: self.target_hw.clone(),
ranges: Vec::new(),
cpes: vec![self.raw.clone()],
purls: Vec::new(),
}
}
}
/// Parse a CPE 2.3 formatted string or CPE 2.2 URI into all components.
pub fn parse_cpe(input: &str) -> Option<Cpe> {
let input = input.trim();
if let Some(rest) = input.strip_prefix("cpe:2.3:") {
parse_cpe23(input, rest)
} else if let Some(rest) = input.strip_prefix("cpe:/") {
parse_cpe22(input, rest)
} else {
None
}
}
fn clean_component(field: &str) -> Option<String> {
match field {
"" | "*" | "-" => None,
value => Some(value.to_owned()),
}
}
fn valid_part(part: &Option<String>) -> bool {
matches!(part.as_deref(), Some("a" | "o" | "h"))
}
/// Split on an unescaped delimiter and unescape backslash escapes.
fn split_escaped(input: &str, delimiter: char) -> Vec<String> {
let mut fields = Vec::new();
let mut current = String::new();
let mut chars = input.chars();
while let Some(ch) = chars.next() {
match ch {
'\\' => {
if let Some(escaped) = chars.next() {
current.push(escaped);
}
}
ch if ch == delimiter => fields.push(std::mem::take(&mut current)),
ch => current.push(ch),
}
}
fields.push(current);
fields
}
fn parse_cpe23(raw: &str, rest: &str) -> Option<Cpe> {
let fields = split_escaped(rest, ':');
if !(3..=12).contains(&fields.len()) {
return None;
}
let part = clean_component(&fields[0]);
if !valid_part(&part) {
return None;
}
let component = |index: usize| fields.get(index).and_then(|field| clean_component(field));
Some(Cpe {
raw: raw.to_owned(),
part,
vendor: component(1),
product: component(2),
version: component(3),
update: component(4),
edition: component(5),
language: component(6),
sw_edition: component(7),
target_sw: component(8),
target_hw: component(9),
target_os: component(10),
other: component(11),
})
}
fn decode_cpe22(field: &str) -> String {
percent_decode_str(field).decode_utf8_lossy().into_owned()
}
/// CPE 2.2 packs the extended components into the edition field, separated by
/// unescaped tildes: `edition~sw_edition~target_sw~target_hw~other`. Split the
/// raw field before percent-decoding so an encoded `%7e` stays literal.
fn unpack_cpe22_edition(field: &str) -> [Option<String>; 5] {
let mut packed = field.split('~').map(|part| {
let decoded = decode_cpe22(part);
clean_component(&decoded)
});
std::array::from_fn(|_| packed.next().flatten())
}
fn parse_cpe22(raw: &str, rest: &str) -> Option<Cpe> {
let fields: Vec<&str> = rest.split(':').collect();
if !(3..=7).contains(&fields.len()) {
return None;
}
let part = clean_component(&decode_cpe22(fields[0]));
if !valid_part(&part) {
return None;
}
let component = |index: usize| {
fields
.get(index)
.map(|field| decode_cpe22(field))
.and_then(|field| clean_component(&field))
};
let [edition, sw_edition, target_sw, target_hw, other] =
unpack_cpe22_edition(fields.get(5).copied().unwrap_or_default());
Some(Cpe {
raw: raw.to_owned(),
part,
vendor: component(1),
product: component(2),
version: component(3),
update: component(4),
edition,
language: component(6),
sw_edition,
target_sw,
target_hw,
target_os: None,
other,
})
}
fn range_value(object: &serde_json::Map<String, Value>, key: &str) -> Option<String> {
match object.get(key).and_then(Value::as_str)? {
"" | "*" | "-" => None,
value => Some(value.to_owned()),
}
}
fn extract_ranges(object: &serde_json::Map<String, Value>) -> Vec<VersionRange> {
let range = VersionRange {
start_including: range_value(object, "versionStartIncluding"),
start_excluding: range_value(object, "versionStartExcluding"),
end_including: range_value(object, "versionEndIncluding"),
end_excluding: range_value(object, "versionEndExcluding"),
};
if range == VersionRange::default() {
Vec::new()
} else {
vec![range]
}
}
fn insert_cpe(
raw: &str,
source: &str,
ranges: &[VersionRange],
observations: &mut BTreeSet<ObservedProduct>,
) {
let Some(cpe) = parse_cpe(raw) else {
return;
};
let mut observed = cpe.to_observed(source);
observed.ranges = ranges.to_vec();
observations.insert(observed);
}
fn walk_criteria(value: &Value, source: &str, observations: &mut BTreeSet<ObservedProduct>) {
match value {
Value::Object(object) => {
let ranges = extract_ranges(object);
for key in ["criteria", "cpe23Uri"] {
if let Some(raw) = object.get(key).and_then(Value::as_str) {
insert_cpe(raw, source, &ranges, observations);
}
}
if let Some(cpes) = object.get("cpes").and_then(Value::as_array) {
for cpe in cpes {
if let Some(raw) = cpe.as_str() {
insert_cpe(raw, source, &ranges, observations);
}
}
}
for (key, item) in object {
if !matches!(key.as_str(), "criteria" | "cpe23Uri" | "cpes") {
walk_criteria(item, source, observations);
}
}
}
Value::Array(items) => {
for item in items {
walk_criteria(item, source, observations);
}
}
_ => {}
}
}
/// Collect canonicalization inputs from an NVD CVE JSON value.
///
/// One observation is produced per `affected` entry and one per CPE criteria
/// (`criteria`, `cpe23Uri`, or `cpes`), with version range endpoints from the
/// enclosing object preserved. Identical observations are deduplicated.
pub fn observations_from_cve(cve: &Value) -> Vec<ObservedProduct> {
let mut observations = BTreeSet::new();
if let Some(configurations) = cve.get("configurations") {
walk_criteria(configurations, "nvd-configurations", &mut observations);
}
if let Some(affected) = cve.get("affected").and_then(Value::as_array) {
for entry in affected {
let Some(object) = entry.as_object() else {
continue;
};
walk_criteria(entry, "nvd-affected-cpe", &mut observations);
let mut observed = ObservedProduct {
source: "nvd-affected".to_owned(),
vendor: object
.get("vendor")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned(),
product: object
.get("product")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned(),
version: object
.get("version")
.and_then(Value::as_str)
.map(str::to_owned),
ranges: extract_ranges(object),
..ObservedProduct::default()
};
observed.cpes = object
.get("cpes")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
observed.purls = object
.get("purls")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.chain(object.get("purl").and_then(Value::as_str))
.map(str::to_owned)
.collect::<BTreeSet<_>>()
.into_iter()
.collect();
observations.insert(observed);
}
}
observations.into_iter().collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_full_cpe23_with_escapes() {
let cpe = parse_cpe(
r"cpe:2.3:a:foo:bar\/baz:1.0:upd:ed:en:swed:target_sw:target_hw:target_os:other",
)
.unwrap();
assert_eq!(cpe.part.as_deref(), Some("a"));
assert_eq!(cpe.vendor.as_deref(), Some("foo"));
assert_eq!(cpe.product.as_deref(), Some("bar/baz"));
assert_eq!(cpe.version.as_deref(), Some("1.0"));
assert_eq!(cpe.update.as_deref(), Some("upd"));
assert_eq!(cpe.edition.as_deref(), Some("ed"));
assert_eq!(cpe.language.as_deref(), Some("en"));
assert_eq!(cpe.sw_edition.as_deref(), Some("swed"));
assert_eq!(cpe.target_sw.as_deref(), Some("target_sw"));
assert_eq!(cpe.target_hw.as_deref(), Some("target_hw"));
assert_eq!(cpe.target_os.as_deref(), Some("target_os"));
assert_eq!(cpe.other.as_deref(), Some("other"));
let underscores = parse_cpe(r"cpe:2.3:a:foo:foo\_bar\\baz:1.0:*:*:*:*:*:*:*").unwrap();
assert_eq!(underscores.product.as_deref(), Some(r"foo_bar\baz"));
}
#[test]
fn parses_cpe22_percent_encoding() {
let cpe = parse_cpe("cpe:/a:foo:bar%20baz:1.0:upd:ed:en").unwrap();
assert_eq!(cpe.product.as_deref(), Some("bar baz"));
assert_eq!(cpe.version.as_deref(), Some("1.0"));
assert_eq!(cpe.language.as_deref(), Some("en"));
assert!(cpe.target_hw.is_none());
}
#[test]
fn parses_cpe22_packed_edition() {
let cpe =
parse_cpe("cpe:/a:acme:widget:1.0:upd:~sw_ed~target_sw~target_hw~other:en").unwrap();
assert_eq!(cpe.part.as_deref(), Some("a"));
assert_eq!(cpe.product.as_deref(), Some("widget"));
assert_eq!(cpe.update.as_deref(), Some("upd"));
assert_eq!(cpe.edition, None);
assert_eq!(cpe.sw_edition.as_deref(), Some("sw_ed"));
assert_eq!(cpe.target_sw.as_deref(), Some("target_sw"));
assert_eq!(cpe.target_hw.as_deref(), Some("target_hw"));
assert_eq!(cpe.other.as_deref(), Some("other"));
assert_eq!(cpe.language.as_deref(), Some("en"));
let plain = parse_cpe("cpe:/a:acme:widget:1.0:upd:ed:en").unwrap();
assert_eq!(plain.edition.as_deref(), Some("ed"));
assert_eq!(plain.sw_edition, None);
}
#[test]
fn absent_components_are_none() {
let cpe = parse_cpe("cpe:2.3:a:acme:widget:-:*:*:*:*:*:*:*").unwrap();
assert_eq!(cpe.version, None);
}
#[test]
fn rejects_invalid_cpes() {
assert!(parse_cpe("nope").is_none());
assert!(parse_cpe("cpe:2.3:x:a:b:1.0:*:*:*:*:*:*:*").is_none());
assert!(parse_cpe("cpe:/x:a:b").is_none());
assert!(parse_cpe("cpe:2.3:a:acme").is_none());
}
#[test]
fn observations_cover_configurations_and_affected() {
let cve = serde_json::json!({
"configurations": [
{"nodes": [{"cpeMatch": [
{"criteria": "cpe:2.3:o:redhat:enterprise_linux:8.0:*:*:*:*:*:*:*",
"versionStartIncluding": "8.0", "versionEndExcluding": "8.6"},
{"criteria": "cpe:2.3:o:redhat:enterprise_linux:8.0:*:*:*:*:*:*:*",
"versionStartIncluding": "8.0", "versionEndExcluding": "8.6"}
]}]},
{"nodes": [{"cpeMatch": [
{"cpe23Uri": "cpe:2.3:a:acme:widget:1.0:*:*:*:*:*:*:*"}
]}]}
],
"affected": [{
"vendor": "Red Hat",
"product": "Red Hat Enterprise Linux 8",
"cpes": ["cpe:2.3:o:redhat:enterprise_linux:8.0:*:*:*:*:*:*:*"],
"purls": ["pkg:rpm/redhat/enterprise-linux@8"]
}]
});
let observations = observations_from_cve(&cve);
assert_eq!(observations.len(), 4);
let ranged = observations
.iter()
.find(|observed| {
observed.source == "nvd-configurations" && observed.product == "enterprise_linux"
})
.expect("configuration observation");
assert_eq!(ranged.ranges.len(), 1);
assert_eq!(ranged.ranges[0].start_including.as_deref(), Some("8.0"));
assert_eq!(ranged.ranges[0].end_excluding.as_deref(), Some("8.6"));
let affected = observations
.iter()
.find(|observed| observed.source == "nvd-affected")
.expect("affected observation");
assert_eq!(affected.vendor, "Red Hat");
assert_eq!(affected.product, "Red Hat Enterprise Linux 8");
assert_eq!(affected.purls, vec!["pkg:rpm/redhat/enterprise-linux@8"]);
assert_eq!(affected.cpes.len(), 1);
}
}