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
//! Base vector implementation.

use crate::parsing::Parser;
use crate::v3::base::exploitability::Exploitability;
use crate::v3::base::impact::Impact;
use crate::v3::base::scope::Scope;
use crate::v3::roundup::roundup;
use serde::{Deserialize, Serialize};
use std::fmt::{Error, Formatter};
use std::str::Split;

pub mod exploitability;
pub mod impact;
pub mod scope;

/// A CVSS V3.0 base vector.
///
/// Per the CVSS specification, this structure contains an Exploitability sub-vector, a Scope field, and an Impact sub-vector.
#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)]
pub struct BaseVector {
    /// The Exploitability sub-vector as defined by the CVSS specification.
    pub exploitability: Exploitability,
    /// The Scope field as defined by the CVSS specification.
    pub scope: Scope,
    /// The Impact sub-vector as defined by the CVSS specification.
    pub impact: Impact,
}

impl BaseVector {
    /// Provides the severity score for the CVSS base vector.
    ///
    /// This score respects the CVSS 3.0 specification, particularly regarding floating-point roundup.
    ///
    /// Calling this method is identical to calling [`CVSS3Vector.score()`] when [`CVSS3Vector.temporal`] and [`CVSS3Vector.environmental`] are set to [`None`].
    ///
    /// [`CVSS3Vector.score()`]: ../struct.CVSS3Vector.html#method.score
    /// [`CVSS3Vector.temporal`]: ../struct.CVSS3Vector.html#structfield.temporal
    /// [`CVSS3Vector.environmental`]: ../struct.CVSS3Vector.html#structfield.environmental
    /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
    pub fn score(&self) -> f64 {
        let impact_score = self.impact.score(self.scope);
        let exploitability_score = self.exploitability.score(self.scope);

        if impact_score > 0.0 {
            match self.scope {
                Scope::Unchanged => roundup(f64::min(impact_score + exploitability_score, 10.0)),
                Scope::Changed => {
                    roundup(f64::min(1.08 * (impact_score + exploitability_score), 10.0))
                }
            }
        } else {
            0.0
        }
    }

    #[doc(hidden)]
    pub fn cvss_prefix() -> &'static str {
        "CVSS:3.0"
    }

    fn parse_prefix(split: &mut Box<Split<char>>) -> Result<(), Vec<&'static str>> {
        static ERR_MSG: &str = "Header (CVSS3.0) is either missing or incorrect.";

        match split.next() {
            None => Err(vec![ERR_MSG]),
            Some(header) => {
                if header == BaseVector::cvss_prefix() {
                    Ok(())
                } else {
                    Err(vec![ERR_MSG])
                }
            }
        }
    }
}

impl Parser for BaseVector {
    fn parse_strict(split: &mut Box<Split<char>>) -> Result<Self, Vec<&'static str>>
    where
        Self: Sized,
    {
        let mut parsers = (None, None, None);
        let mut errors = Vec::new();

        let res = BaseVector::parse_prefix(split);
        if res.is_err() {
            errors.append(&mut res.unwrap_err());
        }

        let res = Exploitability::parse_strict(split);
        if res.is_ok() {
            parsers.0 = res.ok();
        } else {
            errors.append(&mut res.unwrap_err());
        }

        let res = Scope::parse_strict(split);
        if res.is_ok() {
            parsers.1 = res.ok();
        } else {
            errors.append(&mut res.unwrap_err());
        }

        let res = Impact::parse_strict(split);
        if res.is_ok() {
            parsers.2 = res.ok();
        } else {
            errors.append(&mut res.unwrap_err());
        }

        if parsers.0.is_some() && parsers.1.is_some() && parsers.2.is_some() {
            Ok(BaseVector {
                exploitability: parsers.0.unwrap(),
                scope: parsers.1.unwrap(),
                impact: parsers.2.unwrap(),
            })
        } else {
            Err(errors)
        }
    }

    fn parse_nonstrict(split: &Box<Split<char>>) -> Result<Self, Vec<&'static str>>
    where
        Self: Sized,
    {
        let mut parsers = (None, None, None);
        let mut errors = Vec::new();

        let res = Exploitability::parse_nonstrict(split);
        if res.is_ok() {
            parsers.0 = res.ok();
        } else {
            errors.append(&mut res.unwrap_err());
        }

        let res = Scope::parse_nonstrict(split);
        if res.is_ok() {
            parsers.1 = res.ok();
        } else {
            errors.append(&mut res.unwrap_err());
        }

        let res = Impact::parse_nonstrict(split);
        if res.is_ok() {
            parsers.2 = res.ok();
        } else {
            errors.append(&mut res.unwrap_err());
        }

        if parsers.0.is_some() && parsers.1.is_some() && parsers.2.is_some() {
            Ok(BaseVector {
                exploitability: parsers.0.unwrap(),
                scope: parsers.1.unwrap(),
                impact: parsers.2.unwrap(),
            })
        } else {
            Err(errors)
        }
    }
}

impl std::fmt::Display for BaseVector {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        write!(
            f,
            "{}/{}/{}/{}",
            BaseVector::cvss_prefix(),
            self.exploitability,
            self.scope,
            self.impact
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_formatting() {
        assert_eq!(
            "CVSS:3.0/AV:N/AC:L/PR:H/UI:N/S:U/C:L/I:L/A:N",
            format!("{}", provide_base_vector1())
        );
    }

    #[test]
    fn test_parsing() {
        // Example provided in CVSS 3.0 specification section "Vector String"
        assert_eq!(
            Ok(provide_base_vector1()),
            BaseVector::parse_strict(&mut Box::new(
                "CVSS:3.0/AV:N/AC:L/PR:H/UI:N/S:U/C:L/I:L/A:N".split('/')
            )),
        );

        // Example provided in CVSS 3.0 specification section "Vector String"
        assert_eq!(
            Ok(provide_base_vector1()),
            BaseVector::parse_nonstrict(&mut Box::new(
                "CVSS:3.0/AV:N/AC:L/PR:H/UI:N/S:U/C:L/I:L/A:N".split('/')
            )),
        );

        // With two fields swapped inside a subvector (exploitability)
        assert!(BaseVector::parse_strict(&mut Box::new(
            "CVSS:3.0/AC:L/AV:N/PR:H/UI:N/S:U/C:L/I:L/A:N".split('/')
        ))
        .is_err());
        assert_eq!(
            Ok(provide_base_vector1()),
            BaseVector::parse_nonstrict(&mut Box::new(
                "CVSS:3.0/AC:L/AV:N/PR:H/UI:N/S:U/C:L/I:L/A:N".split('/')
            )),
        );

        // With two fields swapped between two subvector (exploitability and impact)
        assert!(BaseVector::parse_strict(&mut Box::new(
            "CVSS:3.0/AC:L/PR:H/UI:N/S:U/C:L/I:L/A:N/AV:N".split('/')
        ))
        .is_err());
        assert_eq!(
            Ok(provide_base_vector1()),
            BaseVector::parse_nonstrict(&mut Box::new(
                "CVSS:3.0/AC:L/PR:H/UI:N/S:U/C:L/I:L/A:N/AV:N".split('/')
            )),
        );

        // Example provided in CVSS 3.0 specification section "Vector String"
        assert!(BaseVector::parse_strict(&mut Box::new(
            "CVSS:3.0/S:U/AV:N/AC:L/PR:H/UI:N/C:L/I:L/A:N/E:F/RL:X".split('/')
        ))
        .is_err());
        assert_eq!(
            Ok(provide_base_vector1()),
            BaseVector::parse_nonstrict(&mut Box::new(
                "CVSS:3.0/S:U/AV:N/AC:L/PR:H/UI:N/C:L/I:L/A:N/E:F/RL:X".split('/')
            )),
        );

        // Sane example with prefix removed
        assert!(BaseVector::parse_strict(&mut Box::new(
            "AV:N/AC:L/PR:H/UI:N/S:U/C:L/I:L/A:N".split('/')
        ))
        .is_err());
        assert_eq!(
            Ok(provide_base_vector1()),
            BaseVector::parse_nonstrict(&mut Box::new(
                "AV:N/AC:L/PR:H/UI:N/S:U/C:L/I:L/A:N".split('/')
            )),
        );

        // Junk entry
        assert!(BaseVector::parse_strict(&mut Box::new("fsjfskhf".split('/'))).is_err());
        assert!(BaseVector::parse_nonstrict(&mut Box::new("fsjfskhf".split('/'))).is_err());

        assert!(BaseVector::parse_strict(&mut Box::new("fs//jf/skhf".split('/'))).is_err());
        assert!(BaseVector::parse_nonstrict(&mut Box::new("fs//jf/skhf".split('/'))).is_err());
    }

    #[test]
    fn test_scoring() {
        assert_eq!(3.8, provide_base_vector1().score());
    }

    // This example is taken from CVSS 3.0 specification section "Vector String".
    fn provide_base_vector1() -> BaseVector {
        BaseVector {
            exploitability: exploitability::tests::provide_exploitability_vector1(),
            scope: Scope::Unchanged,
            impact: impact::tests::provide_impact_vector1(),
        }
    }
}