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

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

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

/// A CVSS V2.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 CVSS2Vector {
    /// Mandatory Base vector.
    pub base: BaseVector,
    /// Optional Temporal vector.
    pub temporal: Option<TemporalVector>,
    /// Optional Environmental vector.
    pub environmental: Option<EnvironmentalVector>,
}

impl CVSS2Vector {
    /// 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(CVSS2Vector {
                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(CVSS2Vector {
                base: parsers.0.unwrap(),
                temporal: parsers.1,
                environmental: parsers.2,
            })
        } else {
            Err(errors)
        }
    }

    /// Provides the severity score for the CVSS vector.
    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 Display for CVSS2Vector {
    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::v2::base::{
        AccessComplexity, AccessVector, Authentication, AvailabilityImpact, ConfidentialityImpact,
        IntegrityImpact,
    };
    use crate::v2::environmental::{
        AvailabilityRequirement, CollateralDamagePotential, ConfidentialityRequirement,
        IntegrityRequirement, TargetDistribution,
    };
    use crate::v2::temporal::{Exploitability, RemediationLevel, ReportConfidence};

    #[test]
    fn test_formatting() {
        // CVE-2002-0392 see CVSS v2 specification section 3.3.1
        assert_eq!(
            "AV:N/AC:L/Au:N/C:N/I:N/A:C/E:F/RL:OF/RC:C/CDP:H/TD:H/CR:M/IR:M/AR:H",
            format!("{}", provide_cvss_vector())
        );
    }

    #[test]
    fn test_parsing() {
        // CVE-2002-0392 see CVSS v2 specification section 3.3.1
        assert_eq!(
            Ok(provide_cvss_vector()),
            CVSS2Vector::parse_strict(
                "AV:N/AC:L/Au:N/C:N/I:N/A:C/E:F/RL:OF/RC:C/CDP:H/TD:H/CR:M/IR:M/AR:H"
            )
        );
        // CVE-2002-0392 see CVSS v2 specification section 3.3.1
        assert_eq!(
            Ok(provide_cvss_vector()),
            CVSS2Vector::parse_nonstrict(
                "AV:N/AC:L/Au:N/C:N/I:N/A:C/E:F/RL:OF/RC:C/CDP:H/TD:H/CR:M/IR:M/AR:H"
            )
        );

        // With two fields swapped inside a subvector (base)
        assert!(CVSS2Vector::parse_strict(
            "AC:L/Au:N/AV:N/C:N/I:N/A:C/E:F/RL:OF/RC:C/CDP:H/TD:H/CR:M/IR:M/AR:H"
        )
        .is_err());
        assert_eq!(
            Ok(provide_cvss_vector()),
            CVSS2Vector::parse_nonstrict(
                "AC:L/Au:N/AV:N/C:N/I:N/A:C/E:F/RL:OF/RC:C/CDP:H/TD:H/CR:M/IR:M/AR:H"
            ),
        );

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

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

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

    fn provide_cvss_vector() -> CVSS2Vector {
        CVSS2Vector {
            base: provide_base_vector1(),
            temporal: Some(provide_temporal_vector1()),
            environmental: Some(provide_environmental_vector1()),
        }
    }

    // CVE-2002-0392 see CVSS v2 specification section 3.3.1
    // Using the "High" variant
    fn provide_environmental_vector1() -> EnvironmentalVector {
        EnvironmentalVector {
            collateral_damage_potential: Some(CollateralDamagePotential::High),
            target_distribution: Some(TargetDistribution::High),
            confidentiality_requirement: Some(ConfidentialityRequirement::Medium),
            integrity_requirement: Some(IntegrityRequirement::Medium),
            availability_requirement: Some(AvailabilityRequirement::High),
        }
    }

    // CVE-2002-0392 see CVSS v2 specification section 3.3.1
    fn provide_temporal_vector1() -> TemporalVector {
        TemporalVector {
            exploitability: Some(Exploitability::Functional),
            remediation_level: Some(RemediationLevel::OfficialFix),
            report_confidence: Some(ReportConfidence::Confirmed),
        }
    }

    // CVE-2002-0392 see CVSS v2 specification section 3.3.1
    fn provide_base_vector1() -> BaseVector {
        BaseVector {
            access_vector: AccessVector::Network,
            access_complexity: AccessComplexity::Low,
            authentication: Authentication::None,
            confidentiality_impact: ConfidentialityImpact::None,
            integrity_impact: IntegrityImpact::None,
            availability_impact: AvailabilityImpact::Complete,
        }
    }
}