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
//! This module provides support for the CVSS 3.0 specification.
//!
//! See [module-level documentation](../index.html) for more details.

use crate::parsing::{OptionalParser, Parser};
use crate::v3::base::BaseVector;
use crate::v3::environmental::EnvironmentalVector;
use crate::v3::temporal::TemporalVector;
use serde::{Deserialize, Serialize};
use std::fmt::{Error, Formatter};

pub mod base;
pub mod environmental;
pub mod roundup;
pub mod temporal;

/// A CVSS V3.0 vector.
///
/// This structure contains a mandatory base vector, an optional temporal vector and an optional environmental vector.
#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)]
pub struct CVSS3Vector {
    /// Mandatory Base vector.
    pub base: BaseVector,
    /// Optional Temporal vector.
    pub temporal: Option<TemporalVector>,
    /// Optional Environmental vector.
    pub environmental: Option<EnvironmentalVector>,
}

impl CVSS3Vector {
    /// Attempts to parse a string slice as a CVSS vector, in strict mode.
    ///
    /// In strict mode, all fields must be in canonical order as defined by the CVSS specification.
    ///  They must be present exactly once (for mandatory fields), or zero or one time for optional fields.
    ///
    /// If parsing fails a list of of errors will be returned in a human readable format.
    pub fn parse_strict(cvss_string: &str) -> Result<Self, Vec<&'static str>>
    where
        Self: Sized,
    {
        let mut split = Box::new(cvss_string.split('/'));

        let mut parsers = (None, None, None);
        let mut errors = Vec::new();

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

        parsers.1 = TemporalVector::parse_optional(&split);
        parsers.2 = EnvironmentalVector::parse_optional(&split);

        if parsers.0.is_some() {
            Ok(CVSS3Vector {
                base: parsers.0.unwrap(),
                temporal: parsers.1,
                environmental: parsers.2,
            })
        } else {
            Err(errors)
        }
    }

    /// Attempts to parse a string slice as a CVSS vector, in non-strict mode.
    ///
    /// In non-strict mode, the parser will make the best out of the input.
    /// Fields do not have to be in the canonical order, and can be repeated (the last occurence of a field will be used).
    /// All mandatory fields (per the CVSS specification) still have to be present in the input.
    ///
    /// If parsing fails a list of of errors will be returned in a human readable format.
    pub fn parse_nonstrict(cvss_string: &str) -> Result<Self, Vec<&'static str>>
    where
        Self: Sized,
    {
        let split = Box::new(cvss_string.split('/'));

        let mut parsers = (None, None, None);
        let mut errors = Vec::new();

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

        parsers.1 = TemporalVector::parse_optional(&split);
        parsers.2 = EnvironmentalVector::parse_optional(&split);

        if parsers.0.is_some() {
            Ok(CVSS3Vector {
                base: parsers.0.unwrap(),
                temporal: parsers.1,
                environmental: parsers.2,
            })
        } else {
            Err(errors)
        }
    }

    /// Provides the severity score for the CVSS vector.
    ///
    /// This score respects the CVSS 3.0 specification, particularly regarding floating-point roundup.
    pub fn score(&self) -> f64 {
        match self.environmental {
            Some(environmental_vector) => environmental_vector.score(self.base, self.temporal),
            None => match self.temporal {
                Some(temporal_vector) => temporal_vector.score(self.base.score()),
                None => self.base.score(),
            },
        }
    }
}

impl std::fmt::Display for CVSS3Vector {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        // Fancy way to write a/b which degrade to a or b, a etc. when any field is missing (as they are all optional)
        let mut fields = Vec::new();

        fields.push(format!("{}", self.base));

        match self.temporal {
            None => (),
            Some(field) => fields.push(format!("{}", field)),
        };

        match self.environmental {
            None => (),
            Some(field) => fields.push(format!("{}", field)),
        };

        write!(f, "{}", fields.join("/"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::v3::base::exploitability::{
        AttackComplexity, AttackVector, Exploitability, PrivilegesRequired, UserInteraction,
    };
    use crate::v3::base::impact::{Availability, Confidentiality, Impact, Integrity};
    use crate::v3::base::scope::Scope;
    use crate::v3::environmental::modified_base::modified_exploitability::{
        ModifiedAttackComplexity, ModifiedAttackVector, ModifiedExploitability,
    };
    use crate::v3::environmental::modified_base::ModifiedBaseVector;
    use crate::v3::environmental::security_requirements::{
        AvailabilityRequirement, ConfidentialityRequirement, IntegrityRequirement,
        SecurityRequirements,
    };
    use crate::v3::temporal::{ExploitCodeMaturity, RemediationLevel, ReportConfidence};

    #[test]
    fn test_formatting() {
        assert_eq!(
            "CVSS:3.0/AV:A/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H/E:F/RL:O/RC:C/CR:H/IR:H/AR:M/MAV:N/MAC:L",
            format!("{}", provide_cvss_vector())
        );
    }

    #[test]
    fn test_parsing() {
        // This example is invented from scratch as the CVSS 3.0 specification does not provide a full vector example.
        assert_eq!(
            Ok(provide_cvss_vector()),
            CVSS3Vector::parse_strict(
                "CVSS:3.0/AV:A/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H/E:F/RL:O/RC:C/CR:H/IR:H/AR:M/MAV:N/MAC:L"),
        );

        // This example is invented from scratch as the CVSS 3.0 specification does not provide a full vector example.
        assert_eq!(
            Ok(provide_cvss_vector()),
            CVSS3Vector::parse_nonstrict(
                "CVSS:3.0/AV:A/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H/E:F/RL:O/RC:C/CR:H/IR:H/AR:M/MAV:N/MAC:L"),
        );

        // With two fields swapped inside a subvector (exploitability)
        assert!(CVSS3Vector::parse_strict(
            "CVSS:3.0/AC:H/AV:A/PR:N/UI:N/S:U/C:H/I:H/A:H/E:F/RL:O/RC:C/CR:H/IR:H/AR:M/MAV:N/MAC:L"
        )
        .is_err());
        assert_eq!(
            Ok(provide_cvss_vector()),
            CVSS3Vector::parse_nonstrict(
                "CVSS:3.0/AC:H/AV:A/PR:N/UI:N/S:U/C:H/I:H/A:H/E:F/RL:O/RC:C/CR:H/IR:H/AR:M/MAV:N/MAC:L"
            ),
        );

        // With two fields swapped between two subvector (exploitability and impact)
        assert!(CVSS3Vector::parse_strict(
            "CVSS:3.0/AC:H/PR:N/UI:N/S:U/C:H/I:H/AV:A/A:H/E:F/RL:O/RC:C/CR:H/IR:H/AR:M/MAV:N/MAC:L"
        )
        .is_err());
        assert_eq!(
            Ok(provide_cvss_vector()),
            CVSS3Vector::parse_nonstrict(
                "CVSS:3.0/AC:H/PR:N/UI:N/S:U/C:H/I:H/AV:A/A:H/E:F/RL:O/RC:C/CR:H/IR:H/AR:M/MAV:N/MAC:L"
                    ),
        );

        // Sane example with prefix removed
        assert!(CVSS3Vector::parse_strict(
            "AV:A/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H/E:F/RL:O/RC:C/CR:H/IR:H/AR:M/MAV:N/MAC:L"
        )
        .is_err());
        assert_eq!(
            Ok(provide_cvss_vector()),
            CVSS3Vector::parse_nonstrict(
                "AV:A/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H/E:F/RL:O/RC:C/CR:H/IR:H/AR:M/MAV:N/MAC:L"
            ),
        );

        // Junk entry
        assert!(CVSS3Vector::parse_strict("fsjfskhf").is_err());
        assert!(CVSS3Vector::parse_nonstrict("fsjfskhf").is_err());

        assert!(CVSS3Vector::parse_strict("fs//jf/skhf").is_err());
        assert!(CVSS3Vector::parse_nonstrict("fs//jf/skhf").is_err());
    }

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

    fn provide_cvss_vector() -> CVSS3Vector {
        CVSS3Vector {
            base: provide_base_vector(),
            temporal: Some(provide_temporal_vector()),
            environmental: Some(provide_environmental_vector()),
        }
    }

    fn provide_base_vector() -> BaseVector {
        BaseVector {
            exploitability: Exploitability {
                attack_vector: AttackVector::Adjacent,
                attack_complexity: AttackComplexity::High,
                privileges_required: PrivilegesRequired::None,
                user_interaction: UserInteraction::None,
            },
            scope: Scope::Unchanged,
            impact: Impact {
                confidentiality: Confidentiality::High,
                integrity: Integrity::High,
                availability: Availability::High,
            },
        }
    }

    fn provide_temporal_vector() -> TemporalVector {
        TemporalVector {
            exploit_code_maturity: Some(ExploitCodeMaturity::Functional),
            remediation_level: Some(RemediationLevel::OfficialFix),
            report_confidence: Some(ReportConfidence::Confirmed),
        }
    }

    fn provide_environmental_vector() -> EnvironmentalVector {
        let modified_base_vector = ModifiedBaseVector {
            modified_exploitability: Some(ModifiedExploitability {
                modified_attack_vector: Some(ModifiedAttackVector::Network),
                modified_attack_complexity: Some(ModifiedAttackComplexity::Low),
                modified_privileges_required: None,
                modified_user_interaction: None,
            }),
            modified_scope: None,
            modified_impact: None,
        };

        let security_requirements = SecurityRequirements {
            confidentiality_requirement: Some(ConfidentialityRequirement::High),
            integrity_requirement: Some(IntegrityRequirement::High),
            availability_requirement: Some(AvailabilityRequirement::Medium),
        };

        EnvironmentalVector {
            security_requirements: Some(security_requirements),
            modified_base: Some(modified_base_vector),
        }
    }
}