Debian Codegraph @

src/v3/base.rs

raw symbols SCIP
1 //! CVSS v3.1 Base Metric Group
2
3 mod a;
4 mod ac;
5 mod av;
6 mod c;
7 mod i;
8 mod pr;
9 mod s;
10 mod ui;
11
12 pub use self::{
13 a::Availability, ac::AttackComplexity, av::AttackVector, c::Confidentiality, i::Integrity,
14 pr::PrivilegesRequired, s::Scope, ui::UserInteraction,
15 };
16
17 use super::Score;
18 use crate::{Error, Metric, MetricType, PREFIX, Result};
19 use alloc::{borrow::ToOwned, vec::Vec};
20 use core::{fmt, str::FromStr};
21
22 #[cfg(feature = "serde")]
23 use {
24 alloc::string::{String, ToString},
25 serde::{Deserialize, Serialize, de, ser},
26 };
27
28 #[cfg(feature = "std")]
29 use crate::Severity;
30
31 /// CVSS v3.1 Base Metric Group
32 ///
33 /// Described in CVSS v3.1 Specification: Section 2:
34 /// <https://www.first.org/cvss/specification-document#t6>
35 ///
36 /// > The Base metric group represents the intrinsic characteristics of a
37 /// > vulnerability that are constant over time and across user environments.
38 /// > It is composed of two sets of metrics: the Exploitability metrics and
39 /// > the Impact metrics.
40 /// >
41 /// > The Exploitability metrics reflect the ease and technical means by which
42 /// > the vulnerability can be exploited. That is, they represent characteristics
43 /// > of *the thing that is vulnerable*, which we refer to formally as the
44 /// > *vulnerable component*. The Impact metrics reflect the direct consequence
45 /// > of a successful exploit, and represent the consequence to the
46 /// > *thing that suffers the impact*, which we refer to formally as the
47 /// > *impacted component*.
48 /// >
49 /// > While the vulnerable component is typically a software application,
50 /// > module, driver, etc. (or possibly a hardware device), the impacted
51 /// > component could be a software application, a hardware device or a network
52 /// > resource. This potential for measuring the impact of a vulnerability other
53 /// > than the vulnerable component, was a key feature introduced with
54 /// > CVSS v3.0. This property is captured by the Scope metric.
55 #[derive(Clone, Debug, Default, Eq, PartialEq)]
56 pub struct Base {
57 /// Minor component of the version
58 pub minor_version: usize,
59
60 /// Attack Vector (AV)
61 pub av: Option<AttackVector>,
62
63 /// Attack Complexity (AC)
64 pub ac: Option<AttackComplexity>,
65
66 /// Privileges Required (PR)
67 pub pr: Option<PrivilegesRequired>,
68
69 /// User Interaction (UI)
70 pub ui: Option<UserInteraction>,
71
72 /// Scope (S)
73 pub s: Option<Scope>,
74
75 /// Confidentiality Impact (C)
76 pub c: Option<Confidentiality>,
77
78 /// Integrity Impact (I)
79 pub i: Option<Integrity>,
80
81 /// Availability Impact (A)
82 pub a: Option<Availability>,
83 }
84
85 impl Base {
86 /// Calculate Base CVSS score: overall value for determining the severity
87 /// of a vulnerability, generally referred to as the "CVSS score".
88 ///
89 /// Described in CVSS v3.1 Specification: Section 2:
90 /// <https://www.first.org/cvss/specification-document#t6>
91 ///
92 /// > When the Base metrics are assigned values by an analyst, the Base
93 /// > equation computes a score ranging from 0.0 to 10.0.
94 /// >
95 /// > Specifically, the Base equation is derived from two sub equations:
96 /// > the Exploitability sub-score equation, and the Impact sub-score
97 /// > equation. The Exploitability sub-score equation is derived from the
98 /// > Base Exploitability metrics, while the Impact sub-score equation is
99 /// > derived from the Base Impact metrics.
100 #[cfg(feature = "std")]
101 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
102 pub fn score(&self) -> Score {
103 let exploitability = self.exploitability().value();
104 let iss = self.impact().value();
105
106 let iss_scoped = if !self.is_scope_changed() {
107 6.42 * iss
108 } else {
109 (7.52 * (iss - 0.029)) - (3.25 * (iss - 0.02).powf(15.0))
110 };
111
112 let score = if iss_scoped <= 0.0 {
113 0.0
114 } else if !self.is_scope_changed() {
115 (iss_scoped + exploitability).min(10.0)
116 } else {
117 (1.08 * (iss_scoped + exploitability)).min(10.0)
118 };
119
120 Score::new(score).roundup()
121 }
122
123 /// Calculate Base Exploitability score: sub-score for measuring
124 /// ease of exploitation.
125 ///
126 /// Described in CVSS v3.1 Specification: Section 2:
127 /// <https://www.first.org/cvss/specification-document#t6>
128 ///
129 /// > The Exploitability metrics reflect the ease and technical means by which
130 /// > the vulnerability can be exploited. That is, they represent characteristics
131 /// > of *the thing that is vulnerable*, which we refer to formally as the
132 /// > *vulnerable component*.
133 pub fn exploitability(&self) -> Score {
134 let av_score = self.av.map(|av| av.score()).unwrap_or(0.0);
135 let ac_score = self.ac.map(|ac| ac.score()).unwrap_or(0.0);
136 let ui_score = self.ui.map(|ui| ui.score()).unwrap_or(0.0);
137 let pr_score = self
138 .pr
139 .map(|pr| pr.scoped_score(self.is_scope_changed()))
140 .unwrap_or(0.0);
141
142 (8.22 * av_score * ac_score * pr_score * ui_score).into()
143 }
144
145 /// Calculate Base Impact Score (ISS): sub-score for measuring the
146 /// consequences of successful exploitation.
147 ///
148 /// Described in CVSS v3.1 Specification: Section 2:
149 /// <https://www.first.org/cvss/specification-document#t6>
150 ///
151 /// > The Impact metrics reflect the direct consequence
152 /// > of a successful exploit, and represent the consequence to the
153 /// > *thing that suffers the impact*, which we refer to formally as the
154 /// > *impacted component*.
155 #[cfg(feature = "std")]
156 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
157 pub fn impact(&self) -> Score {
158 let c_score = self.c.map(|c| c.score()).unwrap_or(0.0);
159 let i_score = self.i.map(|i| i.score()).unwrap_or(0.0);
160 let a_score = self.a.map(|a| a.score()).unwrap_or(0.0);
161 (1.0 - ((1.0 - c_score) * (1.0 - i_score) * (1.0 - a_score)).abs()).into()
162 }
163
164 /// Iterate over all defined Base metrics
165 pub fn metrics(&self) -> impl Iterator<Item = (MetricType, &dyn fmt::Debug)> {
166 [
167 (
168 MetricType::AV,
169 self.av.as_ref().map(|m| m as &dyn fmt::Debug),
170 ),
171 (
172 MetricType::AC,
173 self.ac.as_ref().map(|m| m as &dyn fmt::Debug),
174 ),
175 (
176 MetricType::PR,
177 self.pr.as_ref().map(|m| m as &dyn fmt::Debug),
178 ),
179 (
180 MetricType::UI,
181 self.ui.as_ref().map(|m| m as &dyn fmt::Debug),
182 ),
183 (MetricType::S, self.s.as_ref().map(|m| m as &dyn fmt::Debug)),
184 (MetricType::C, self.c.as_ref().map(|m| m as &dyn fmt::Debug)),
185 (MetricType::I, self.i.as_ref().map(|m| m as &dyn fmt::Debug)),
186 (MetricType::A, self.a.as_ref().map(|m| m as &dyn fmt::Debug)),
187 ]
188 .into_iter()
189 .filter_map(|(name, metric)| metric.as_ref().map(|&m| (name, m)))
190 }
191
192 /// Calculate Base CVSS `Severity` according to the
193 /// Qualitative Severity Rating Scale (i.e. Low / Medium / High / Critical)
194 ///
195 /// Described in CVSS v3.1 Specification: Section 5:
196 /// <https://www.first.org/cvss/specification-document#t17>
197 #[cfg(feature = "std")]
198 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
199 pub fn severity(&self) -> Severity {
200 self.score().severity()
201 }
202
203 /// Has the scope changed?
204 fn is_scope_changed(&self) -> bool {
205 self.s.map(|s| s.is_changed()).unwrap_or(false)
206 }
207 }
208
209 macro_rules! write_metrics {
210 ($f:expr, $($metric:expr),+) => {
211 $(
212 if let Some(metric) = $metric {
213 write!($f, "/{}", metric)?;
214 }
215 )+
216 };
217 }
218
219 impl fmt::Display for Base {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 write!(f, "{}:3.{}", PREFIX, self.minor_version)?;
222 write_metrics!(
223 f, self.av, self.ac, self.pr, self.ui, self.s, self.c, self.i, self.a
224 );
225 Ok(())
226 }
227 }
228
229 impl FromStr for Base {
230 type Err = Error;
231
232 fn from_str(s: &str) -> Result<Self> {
233 let component_vec = s
234 .split('/')
235 .map(|component| {
236 let mut parts = component.split(':');
237
238 let id = parts.next().ok_or_else(|| Error::InvalidComponent {
239 component: component.to_owned(),
240 })?;
241
242 let value = parts.next().ok_or_else(|| Error::InvalidComponent {
243 component: component.to_owned(),
244 })?;
245
246 if parts.next().is_some() {
247 return Err(Error::InvalidComponent {
248 component: component.to_owned(),
249 });
250 }
251
252 Ok((id, value))
253 })
254 .collect::<Result<Vec<_>>>()?;
255
256 let mut components = component_vec.iter();
257 let &(id, version_string) = components.next().ok_or(Error::InvalidPrefix {
258 prefix: s.to_owned(),
259 })?;
260
261 if id != PREFIX {
262 return Err(Error::InvalidPrefix {
263 prefix: id.to_owned(),
264 });
265 }
266
267 let mut metrics = Self {
268 minor_version: match version_string {
269 "3.0" => 0,
270 "3.1" => 1,
271 _ => {
272 return Err(Error::UnsupportedVersion {
273 version: version_string.to_owned(),
274 });
275 }
276 },
277 ..Default::default()
278 };
279
280 for &component in components {
281 let id = component.0.to_ascii_uppercase();
282 let value = component.1.to_ascii_uppercase();
283
284 match id.parse::<MetricType>()? {
285 MetricType::AV => metrics.av = Some(value.parse()?),
286 MetricType::AC => metrics.ac = Some(value.parse()?),
287 MetricType::PR => metrics.pr = Some(value.parse()?),
288 MetricType::UI => metrics.ui = Some(value.parse()?),
289 MetricType::S => metrics.s = Some(value.parse()?),
290 MetricType::C => metrics.c = Some(value.parse()?),
291 MetricType::I => metrics.i = Some(value.parse()?),
292 MetricType::A => metrics.a = Some(value.parse()?),
293 }
294 }
295
296 Ok(metrics)
297 }
298 }
299
300 #[cfg(feature = "serde")]
301 #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
302 impl<'de> Deserialize<'de> for Base {
303 fn deserialize<D: de::Deserializer<'de>>(
304 deserializer: D,
305 ) -> core::result::Result<Self, D::Error> {
306 String::deserialize(deserializer)?
307 .parse()
308 .map_err(de::Error::custom)
309 }
310 }
311
312 #[cfg(feature = "serde")]
313 #[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
314 impl Serialize for Base {
315 fn serialize<S: ser::Serializer>(
316 &self,
317 serializer: S,
318 ) -> core::result::Result<S::Ok, S::Error> {
319 self.to_string().serialize(serializer)
320 }
321 }