From c7268e02dbf6b9a82fa15630994380bd49f62107 Mon Sep 17 00:00:00 2001 From: Sergio Date: Tue, 29 Sep 2020 09:41:48 +0200 Subject: [PATCH 1/9] Finding (+template): asvs-masvs --- .../f82048e51f97_finding_asvs_masvs.py | 35 +++++++++++++++++++ sarna/forms/finding_template.py | 23 +++++++++--- sarna/model/finding.py | 3 ++ sarna/model/finding_template.py | 3 ++ 4 files changed, 60 insertions(+), 4 deletions(-) create mode 100644 migrations/versions/f82048e51f97_finding_asvs_masvs.py diff --git a/migrations/versions/f82048e51f97_finding_asvs_masvs.py b/migrations/versions/f82048e51f97_finding_asvs_masvs.py new file mode 100644 index 0000000..28dde12 --- /dev/null +++ b/migrations/versions/f82048e51f97_finding_asvs_masvs.py @@ -0,0 +1,35 @@ +"""finding: asvs + masvs + +Revision ID: f82048e51f97 +Revises: 3277e0ef1496 +Create Date: 2020-09-29 10:19:36.507193 + +""" +from alembic import op +import sqlalchemy as sa +import sarna + + +# revision identifiers, used by Alembic. +revision = 'f82048e51f97' +down_revision = '3277e0ef1496' +branch_labels = None +depends_on = None + + +def upgrade(): +# ### commands auto generated by Alembic - please adjust! ### + op.add_column('finding', sa.Column('asvs', sa.String(length=8), nullable=True)) + op.add_column('finding', sa.Column('masvs', sa.String(length=8), nullable=True)) + op.add_column('finding_template', sa.Column('asvs', sa.String(length=8), nullable=True)) + op.add_column('finding_template', sa.Column('masvs', sa.String(length=8), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): +# ### commands auto generated by Alembic - please adjust! ### + op.drop_column('finding', 'masvs') + op.drop_column('finding', 'asvs') + op.drop_column('finding_template', 'masvs') + op.drop_column('finding_template', 'asvs') + # ### end Alembic commands ### diff --git a/sarna/forms/finding_template.py b/sarna/forms/finding_template.py index a3ca3a0..0c00785 100644 --- a/sarna/forms/finding_template.py +++ b/sarna/forms/finding_template.py @@ -1,4 +1,4 @@ -from wtforms import validators +from wtforms import validators, StringField from sarna.forms.base_entity_form import BaseEntityForm from sarna.model.finding_template import FindingTemplate, FindingTemplateTranslation, Solution @@ -8,12 +8,27 @@ class FindingTemplateCreateNewForm( BaseEntityForm(FindingTemplate, hide_attrs={'cvss_v3_score', 'cvss_v3_vector'}), BaseEntityForm(FindingTemplateTranslation, skip_pk=False) ): - pass - + masvs = StringField( + label = "MASVS - OWASP Mobile Application Security Verification Standard Requirement #", + render_kw = {'placeholder': '0.0.0'}, + validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')] + ) + asvs = StringField( + label = "ASVS - OWASP Application Security Verification Standard Requirement #", + render_kw = {'placeholder': '0.0.0'}, + validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')]) class FindingTemplateEditForm(BaseEntityForm(FindingTemplate, hide_attrs={'cvss_v3_score', 'cvss_v3_vector'})): - pass + masvs = StringField( + label = "MASVS - OWASP Mobile Application Security Verification Standard Requirement #", + render_kw = {'placeholder': '0.0.0'}, + validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')] + ) + asvs = StringField( + label = "ASVS - OWASP Application Security Verification Standard Requirement #", + render_kw={'placeholder': '0.0.0'}, + validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')]) class FindingTemplateAddTranslationForm(BaseEntityForm( FindingTemplateTranslation, diff --git a/sarna/model/finding.py b/sarna/model/finding.py index 7a2201a..33d2c09 100644 --- a/sarna/model/finding.py +++ b/sarna/model/finding.py @@ -186,6 +186,9 @@ def cvss_v3_severity(self): @property def client_finding_code(self): return self.assessment.client.format_finding_code(self) + + asvs = db.Column(db.String(8)) + masvs = db.Column(db.String(8)) @classmethod def build_from_template(cls, template: FindingTemplate, assessment: Assessment): diff --git a/sarna/model/finding_template.py b/sarna/model/finding_template.py index 544707b..433bf54 100644 --- a/sarna/model/finding_template.py +++ b/sarna/model/finding_template.py @@ -48,6 +48,9 @@ def cvss_v3_severity(self): else: return Score.Critical + asvs = db.Column(db.String(8)) + masvs = db.Column(db.String(8)) + class FindingTemplateTranslation(Base, db.Model): lang = db.Column(Enum(Language), primary_key=True) From 367866051c9b3b4afafdec96ea91d8cdc2408aa9 Mon Sep 17 00:00:00 2001 From: fillodemanuel <63927071+fillodemanuel@users.noreply.github.com> Date: Tue, 29 Sep 2020 17:30:10 +0200 Subject: [PATCH 2/9] Finding (+template): asvs-masvs (#11) --- .../f82048e51f97_finding_asvs_masvs.py | 35 +++++++++++++++++++ sarna/forms/finding_template.py | 23 +++++++++--- sarna/model/finding.py | 3 ++ sarna/model/finding_template.py | 3 ++ 4 files changed, 60 insertions(+), 4 deletions(-) create mode 100644 migrations/versions/f82048e51f97_finding_asvs_masvs.py diff --git a/migrations/versions/f82048e51f97_finding_asvs_masvs.py b/migrations/versions/f82048e51f97_finding_asvs_masvs.py new file mode 100644 index 0000000..28dde12 --- /dev/null +++ b/migrations/versions/f82048e51f97_finding_asvs_masvs.py @@ -0,0 +1,35 @@ +"""finding: asvs + masvs + +Revision ID: f82048e51f97 +Revises: 3277e0ef1496 +Create Date: 2020-09-29 10:19:36.507193 + +""" +from alembic import op +import sqlalchemy as sa +import sarna + + +# revision identifiers, used by Alembic. +revision = 'f82048e51f97' +down_revision = '3277e0ef1496' +branch_labels = None +depends_on = None + + +def upgrade(): +# ### commands auto generated by Alembic - please adjust! ### + op.add_column('finding', sa.Column('asvs', sa.String(length=8), nullable=True)) + op.add_column('finding', sa.Column('masvs', sa.String(length=8), nullable=True)) + op.add_column('finding_template', sa.Column('asvs', sa.String(length=8), nullable=True)) + op.add_column('finding_template', sa.Column('masvs', sa.String(length=8), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): +# ### commands auto generated by Alembic - please adjust! ### + op.drop_column('finding', 'masvs') + op.drop_column('finding', 'asvs') + op.drop_column('finding_template', 'masvs') + op.drop_column('finding_template', 'asvs') + # ### end Alembic commands ### diff --git a/sarna/forms/finding_template.py b/sarna/forms/finding_template.py index a3ca3a0..0c00785 100644 --- a/sarna/forms/finding_template.py +++ b/sarna/forms/finding_template.py @@ -1,4 +1,4 @@ -from wtforms import validators +from wtforms import validators, StringField from sarna.forms.base_entity_form import BaseEntityForm from sarna.model.finding_template import FindingTemplate, FindingTemplateTranslation, Solution @@ -8,12 +8,27 @@ class FindingTemplateCreateNewForm( BaseEntityForm(FindingTemplate, hide_attrs={'cvss_v3_score', 'cvss_v3_vector'}), BaseEntityForm(FindingTemplateTranslation, skip_pk=False) ): - pass - + masvs = StringField( + label = "MASVS - OWASP Mobile Application Security Verification Standard Requirement #", + render_kw = {'placeholder': '0.0.0'}, + validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')] + ) + asvs = StringField( + label = "ASVS - OWASP Application Security Verification Standard Requirement #", + render_kw = {'placeholder': '0.0.0'}, + validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')]) class FindingTemplateEditForm(BaseEntityForm(FindingTemplate, hide_attrs={'cvss_v3_score', 'cvss_v3_vector'})): - pass + masvs = StringField( + label = "MASVS - OWASP Mobile Application Security Verification Standard Requirement #", + render_kw = {'placeholder': '0.0.0'}, + validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')] + ) + asvs = StringField( + label = "ASVS - OWASP Application Security Verification Standard Requirement #", + render_kw={'placeholder': '0.0.0'}, + validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')]) class FindingTemplateAddTranslationForm(BaseEntityForm( FindingTemplateTranslation, diff --git a/sarna/model/finding.py b/sarna/model/finding.py index 7a2201a..33d2c09 100644 --- a/sarna/model/finding.py +++ b/sarna/model/finding.py @@ -186,6 +186,9 @@ def cvss_v3_severity(self): @property def client_finding_code(self): return self.assessment.client.format_finding_code(self) + + asvs = db.Column(db.String(8)) + masvs = db.Column(db.String(8)) @classmethod def build_from_template(cls, template: FindingTemplate, assessment: Assessment): diff --git a/sarna/model/finding_template.py b/sarna/model/finding_template.py index 544707b..433bf54 100644 --- a/sarna/model/finding_template.py +++ b/sarna/model/finding_template.py @@ -48,6 +48,9 @@ def cvss_v3_severity(self): else: return Score.Critical + asvs = db.Column(db.String(8)) + masvs = db.Column(db.String(8)) + class FindingTemplateTranslation(Base, db.Model): lang = db.Column(Enum(Language), primary_key=True) From b4182d081a677e3e97514faa85b63f39021d546a Mon Sep 17 00:00:00 2001 From: fillodemanuel <63927071+fillodemanuel@users.noreply.github.com> Date: Tue, 29 Sep 2020 17:39:59 +0200 Subject: [PATCH 3/9] Asssessment: added application and bug tracking fields. (#12) --- ...2a2c18ff68c6_assessment_app_bugtracking.py | 31 +++++++++++++++++++ sarna/forms/assessment.py | 4 ++- sarna/model/assessment.py | 4 +++ 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 migrations/versions/2a2c18ff68c6_assessment_app_bugtracking.py diff --git a/migrations/versions/2a2c18ff68c6_assessment_app_bugtracking.py b/migrations/versions/2a2c18ff68c6_assessment_app_bugtracking.py new file mode 100644 index 0000000..86b0504 --- /dev/null +++ b/migrations/versions/2a2c18ff68c6_assessment_app_bugtracking.py @@ -0,0 +1,31 @@ +"""assessment: app+bugtracking + +Revision ID: 2a2c18ff68c6 +Revises: f82048e51f97 +Create Date: 2020-09-29 11:08:17.116023 + +""" +from alembic import op +import sqlalchemy as sa +import sarna + + +# revision identifiers, used by Alembic. +revision = '2a2c18ff68c6' +down_revision = 'f82048e51f97' +branch_labels = None +depends_on = None + + +def upgrade(): +# ### commands auto generated by Alembic - please adjust! ### + op.add_column('assessment', sa.Column('application', sa.String(length=64), nullable=False)) + op.add_column('assessment', sa.Column('bugtracking', sa.String(length=64), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): +# ### commands auto generated by Alembic - please adjust! ### + op.drop_column('assessment', 'bugtracking') + op.drop_column('assessment', 'application') + # ### end Alembic commands ### diff --git a/sarna/forms/assessment.py b/sarna/forms/assessment.py index d2fc6f6..0538033 100644 --- a/sarna/forms/assessment.py +++ b/sarna/forms/assessment.py @@ -1,6 +1,6 @@ from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileRequired -from wtforms import SelectMultipleField, TextAreaField +from wtforms import SelectMultipleField, TextAreaField, StringField from wtforms.validators import Optional from sarna.auxiliary.upload_helpers import is_valid_evidence @@ -16,6 +16,8 @@ class AssessmentForm(BaseEntityForm(Assessment)): coerce=User.coerce, validators=[Optional(), user_is_auditor] ) + bugtracking = StringField(label='Bug Tracking ticket #', render_kw={'placeholder': 'APPSECSER-XXX'}) + application = StringField(label='Application to assess', render_kw={'placeholder': 'APPWEB-MyApp'}) class FindingEditForm(BaseEntityForm(Finding, skip_attrs={'name', 'client_finding_id'}, diff --git a/sarna/model/assessment.py b/sarna/model/assessment.py index ce2245e..0da359b 100644 --- a/sarna/model/assessment.py +++ b/sarna/model/assessment.py @@ -61,6 +61,8 @@ class Assessment(Base, db.Model): AttributeConfiguration(name='status', **supported_serialization), AttributeConfiguration(name='client', **supported_serialization), AttributeConfiguration(name='findings', **supported_serialization), + AttributeConfiguration(name='application', **supported_serialization), + AttributeConfiguration(name='bugtracking', **supported_serialization), ] id = db.Column(db.Integer, primary_key=True) @@ -70,6 +72,8 @@ class Assessment(Base, db.Model): lang = db.Column(Enum(Language), nullable=False) type = db.Column(Enum(AssessmentType), nullable=False) status = db.Column(Enum(AssessmentStatus), nullable=False) + application = db.Column(db.String(64), nullable=False) + bugtracking = db.Column(db.String(64), nullable=True) client_id = db.Column( db.Integer, From 9479464bd696a3573f7bbb9193c2b4d15963e965 Mon Sep 17 00:00:00 2001 From: fillodemanuel <63927071+fillodemanuel@users.noreply.github.com> Date: Tue, 29 Sep 2020 17:52:24 +0200 Subject: [PATCH 4/9] Assessment: SCA + SAST (#13) --- .../44c6c91dd3c4_assessment_sca_sast.py | 31 +++++++++++++++++++ sarna/model/assessment.py | 6 +++- sarna/model/enums/__init__.py | 3 +- sarna/model/enums/analysis.py | 6 ++++ 4 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 migrations/versions/44c6c91dd3c4_assessment_sca_sast.py create mode 100644 sarna/model/enums/analysis.py diff --git a/migrations/versions/44c6c91dd3c4_assessment_sca_sast.py b/migrations/versions/44c6c91dd3c4_assessment_sca_sast.py new file mode 100644 index 0000000..4f0b464 --- /dev/null +++ b/migrations/versions/44c6c91dd3c4_assessment_sca_sast.py @@ -0,0 +1,31 @@ +"""assessment: sca+sast + +Revision ID: 44c6c91dd3c4 +Revises: 2a2c18ff68c6 +Create Date: 2020-09-29 12:30:57.358608 + +""" +from alembic import op +import sqlalchemy as sa +import sarna + + +# revision identifiers, used by Alembic. +revision = '44c6c91dd3c4' +down_revision = '2a2c18ff68c6' +branch_labels = None +depends_on = None + + +def upgrade(): +# ### commands auto generated by Alembic - please adjust! ### + op.add_column('assessment', sa.Column('sast', sarna.model.sql_types.enum.Enum(sarna.model.enums.analysis.AnalysisResultType), nullable=False)) + op.add_column('assessment', sa.Column('sca', sarna.model.sql_types.enum.Enum(sarna.model.enums.analysis.AnalysisResultType), nullable=False)) + # ### end Alembic commands ### + + +def downgrade(): +# ### commands auto generated by Alembic - please adjust! ### + op.drop_column('assessment', 'sca') + op.drop_column('assessment', 'sast') + # ### end Alembic commands ### \ No newline at end of file diff --git a/sarna/model/assessment.py b/sarna/model/assessment.py index 0da359b..73c1aa6 100644 --- a/sarna/model/assessment.py +++ b/sarna/model/assessment.py @@ -8,7 +8,7 @@ from sarna.core.config import config from sarna.model.base import Base, db, supported_serialization from sarna.model.client import Client -from sarna.model.enums import Language, AssessmentType, AssessmentStatus, Score, FindingStatus +from sarna.model.enums import Language, AssessmentType, AssessmentStatus, Score, FindingStatus, AnalysisResultType from sarna.model.sql_types import Enum, GUID __all__ = ['Assessment', 'Image', 'auditor_approval', 'assessment_audit'] @@ -63,6 +63,8 @@ class Assessment(Base, db.Model): AttributeConfiguration(name='findings', **supported_serialization), AttributeConfiguration(name='application', **supported_serialization), AttributeConfiguration(name='bugtracking', **supported_serialization), + AttributeConfiguration(name='sca', **supported_serialization), + AttributeConfiguration(name='sast', **supported_serialization), ] id = db.Column(db.Integer, primary_key=True) @@ -74,6 +76,8 @@ class Assessment(Base, db.Model): status = db.Column(Enum(AssessmentStatus), nullable=False) application = db.Column(db.String(64), nullable=False) bugtracking = db.Column(db.String(64), nullable=True) + sast = db.Column(Enum(AnalysisResultType), nullable=False) + sca = db.Column(Enum(AnalysisResultType), nullable=False) client_id = db.Column( db.Integer, diff --git a/sarna/model/enums/__init__.py b/sarna/model/enums/__init__.py index dca7e7e..f695d0b 100644 --- a/sarna/model/enums/__init__.py +++ b/sarna/model/enums/__init__.py @@ -5,8 +5,9 @@ from .report import SequenceName from .score import Score from .user import UserType, AuthSource +from .analysis import AnalysisResultType __all__ = [ 'UserType', 'AuthSource', 'AssessmentStatus', 'AssessmentType', 'OWISAMCategory', 'OWASPCategory', - 'FindingStatus', 'FindingType', 'Language', 'Score', 'SequenceName' + 'FindingStatus', 'FindingType', 'Language', 'Score', 'SequenceName', 'AnalysisResultType' ] diff --git a/sarna/model/enums/analysis.py b/sarna/model/enums/analysis.py new file mode 100644 index 0000000..8b6261c --- /dev/null +++ b/sarna/model/enums/analysis.py @@ -0,0 +1,6 @@ +from sarna.model.enums.base_choice import BaseChoice + +class AnalysisResultType(BaseChoice): + Failed = 1 + Passed = 2 + Missing = 3 \ No newline at end of file From 9183ccbcc2001ccf24916e7b1df6465dabf77877 Mon Sep 17 00:00:00 2001 From: fillodemanuel <63927071+fillodemanuel@users.noreply.github.com> Date: Tue, 29 Sep 2020 18:01:18 +0200 Subject: [PATCH 5/9] CVSS: Temporal & Environmental (#14) * CVSS: temporal and environmental scores. --- static/js/cvss.js | 814 ++++++++++++++++++++++---------- static/js/cvsscalc31.js | 753 +++++++++++++++++++++++++++++ templates/base.html | 1 + templates/findings/details.html | 2 +- templates/findings/new.html | 43 +- 5 files changed, 1357 insertions(+), 256 deletions(-) create mode 100644 static/js/cvsscalc31.js diff --git a/static/js/cvss.js b/static/js/cvss.js index 88c1723..df7c5fa 100644 --- a/static/js/cvss.js +++ b/static/js/cvss.js @@ -52,15 +52,20 @@ Usage: */ -var CVSS = function (id, options) { +/* + * This JS file has been modified to include temporal and environmental scores in the CVSS calculation. + * Calculation is done through the use of first.org JS: https://www.first.org/cvss/calculator/cvsscalc31.js + * + * Sergio García Spínola + * 24/09/2020 +*/ + +const CVSS = function (id, options, showGroups) { + this.options = options; - this.wId = id; - var e = function (tag) { - return document.createElement(tag); - }; // Base Group - this.bg = { + baseGroup = { AV: 'Attack Vector', AC: 'Attack Complexity', PR: 'Privileges Required', @@ -68,11 +73,48 @@ var CVSS = function (id, options) { S: 'Scope', C: 'Confidentiality', I: 'Integrity', - A: 'Availability' + A: 'Availability' + }; + + // Temporal Group + tempGroup = { + //...baseGroup, + E: 'Exploit Code Maturity', + RL: 'Remediation Level', + RC: 'Report Confidence', + }; + + // Environmental Group + envGroup = { + //...tempGroup, + CR: 'Confidentiality Requirement', + IR: 'Integrity Requirement', + AR: 'Availability Requirement', + MAV: 'Modified Attack Vector', + MAC: 'Modified Attack Complexity', + MPR: 'Modified Privileges Required', + MUI: 'Modified User Interaction', + MS: 'Modified Scope', + MC: 'Modified Confidentiality', + MI: 'Modified Integrity', + MA: 'Modified Availability' }; + // All Groups + allGroup = { + base: { + ...baseGroup + }, + temp: { + ...tempGroup + }, + env: { + ...envGroup + } + } + // Base Metrics - this.bm = { + baseMetrics = { AV: { N: { l: 'Network', @@ -177,11 +219,273 @@ var CVSS = function (id, options) { l: 'None', d: "Good: There is no impact to availability within the impacted component." } + }, + }; + + // Temporal Metrics + tempMetrics = { + //...baseMetrics, + E: { + X: { + l: 'Not Defined', + d: "Assigning this value indicates there is insufficient information to choose one of the other values, and has no impact on the overall Temporal Score, i.e., it has the same effect on scoring as assigning High." + }, + U: { + l: 'Unproven', + d: "No exploit code is available, or an exploit is theoretical." + }, + P: { + l: 'Proof-of-Concept', + d: "Proof-of-concept exploit code is available, or an attack demonstration is not practical for most systems. The code or technique is not functional in all situations and may require substantial modification by a skilled attacker." + }, + F: { + l: 'Functional', + d: "Functional exploit code is available. The code works in most situations where the vulnerability exists." + }, + H: { + l: 'High', + d: "Functional autonomous code exists, or no exploit is required (manual trigger) and details are widely available. Exploit code works in every situation, or is actively being delivered via an autonomous agent (such as a worm or virus). Network-connected systems are likely to encounter scanning or exploitation attempts. Exploit development has reached the level of reliable, widely-available, easy-to-use automated tools." + } + }, + RL: { + X: { + l: 'Not Defined', + d: "Assigning this value indicates there is insufficient information to choose one of the other values, and has no impact on the overall Temporal Score, i.e., it has the same effect on scoring as assigning Unavailable." + }, + O: { + l: 'Official Fix', + d: "A complete vendor solution is available. Either the vendor has issued an official patch, or an upgrade is available." + }, + T: { + l: 'Temporary Fix', + d: "There is an official but temporary fix available. This includes instances where the vendor issues a temporary hotfix, tool, or workaround." + }, + W: { + l: 'Workaround', + d: "There is an unofficial, non-vendor solution available. In some cases, users of the affected technology will create a patch of their own or provide steps to work around or otherwise mitigate the vulnerability." + }, + U: { + l: 'Unavailable', + d: "There is either no solution available or it is impossible to apply." + } + }, + RC: { + X: { + l: 'Not Defined', + d: "Assigning this value indicates there is insufficient information to choose one of the other values, and has no impact on the overall Temporal Score, i.e., it has the same effect on scoring as assigning Confirmed." + }, + U: { + l: 'Unknown', + d: "There are reports of impacts that indicate a vulnerability is present. The reports indicate that the cause of the vulnerability is unknown, or reports may differ on the cause or impacts of the vulnerability. Reporters are uncertain of the true nature of the vulnerability, and there is little confidence in the validity of the reports or whether a static Base score can be applied given the differences described. An example is a bug report which notes that an intermittent but non-reproducible crash occurs, with evidence of memory corruption suggesting that denial of service, or possible more serious impacts, may result." + }, + R: { + l: 'Reasonable', + d: "Significant details are published, but researchers either do not have full confidence in the root cause, or do not have access to source code to fully confirm all of the interactions that may lead to the result. Reasonable confidence exists, however, that the bug is reproducible and at least one impact is able to be verified (Proof-of-concept exploits may provide this). An example is a detailed write-up of research into a vulnerability with an explanation (possibly obfuscated or 'left as an exercise to the reader') that gives assurances on how to reproduce the results." + }, + C: { + l: 'Confirmed', + d: "Detailed reports exist, or functional reproduction is possible (functional exploits may provide this). Source code is available to independently verify the assertions of the research, or the author or vendor of the affected code has confirmed the presence of the vulnerability." + } } }; - this.bme = {}; - this.bmgReg = { + // Environmental Metrics + envMetrics = { + //...tempMetrics, + CR: { + X: { + l: 'Not Defined', + d: "Assigning this value indicates there is insufficient information to choose one of the other values, and has no impact on the overall Environmental Score, i.e., it has the same effect on scoring as assigning Medium." + }, + L: { + l: 'Low', + d: "Loss of Confidentiality is likely to have only a limited adverse effect on the organization or individuals associated with the organization (e.g., employees, customers)." + }, + M: { + l: 'Medium', + d: "Assigning this value to the metric will not influence the score." + }, + H: { + l: 'High', + d: "Loss of Confidentiality is likely to have a catastrophic adverse effect on the organization or individuals associated with the organization (e.g., employees, customers)." + } + }, + IR: { + X: { + l: 'Not Defined', + d: "Assigning this value indicates there is insufficient information to choose one of the other values, and has no impact on the overall Environmental Score, i.e., it has the same effect on scoring as assigning Medium." + }, + L: { + l: 'Low', + d: "Loss of Integrity is likely to have only a limited adverse effect on the organization or individuals associated with the organization (e.g., employees, customers)." + }, + M: { + l: 'Medium', + d: "Assigning this value to the metric will not influence the score." + }, + H: { + l: 'High', + d: "Loss of Integrity is likely to have a catastrophic adverse effect on the organization or individuals associated with the organization (e.g., employees, customers)." + } + }, + AR: { + X: { + l: 'Not Defined', + d: "Assigning this value indicates there is insufficient information to choose one of the other values, and has no impact on the overall Environmental Score, i.e., it has the same effect on scoring as assigning Medium." + }, + L: { + l: 'Low', + d: "Loss of Availability is likely to have only a limited adverse effect on the organization or individuals associated with the organization (e.g., employees, customers)." + }, + M: { + l: 'Medium', + d: "Assigning this value to the metric will not influence the score." + }, + H: { + l: 'High', + d: "Loss of Availability is likely to have a catastrophic adverse effect on the organization or individuals associated with the organization (e.g., employees, customers)." + } + }, + MAV: { + X: { + l: 'Not Defined', + d: "The value assigned to the corresponding Base metric is used." + }, + N: { + l: 'Network', + d: "The vulnerable component is bound to the network stack and the set of possible attackers extends beyond the other options listed, up to and including the entire Internet. Such a vulnerability is often termed 'remotely exploitable' and can be thought of as an attack being exploitable at the protocol level one or more network hops away." + }, + A: { + l: 'Adjacent Network', + d: "The vulnerable component is bound to the network stack, but the attack is limited at the protocol level to a logically adjacent topology. This can mean an attack must be launched from the same shared physical (e.g., Bluetooth or IEEE 802.11) or logical (e.g., local IP subnet) network, or from within a secure or otherwise limited administrative domain (e.g., MPLS, secure VPN)." + }, + L: { + l: 'Local', + d: "The vulnerable component is not bound to the network stack and the attacker’s path is via read/write/execute capabilities. Either: the attacker exploits the vulnerability by accessing the target system locally (e.g., keyboard, console), or remotely (e.g., SSH); or the attacker relies on User Interaction by another person to perform actions required to exploit the vulnerability (e.g., tricking a legitimate user into opening a malicious document)." + }, + P: { + l: 'Physical', + d: "The attack requires the attacker to physically touch or manipulate the vulnerable component. Physical interaction may be brief or persistent." + } + }, + MAC: { + X: { + l: 'Not Defined', + d: "The value assigned to the corresponding Base metric is used." + }, + L: { + l: 'Low', + d: "Specialized access conditions or extenuating circumstances do not exist. An attacker can expect repeatable success against the vulnerable component." + }, + H: { + l: 'High', + d: "A successful attack depends on conditions beyond the attacker's control. That is, a successful attack cannot be accomplished at will, but requires the attacker to invest in some measurable amount of effort in preparation or execution against the vulnerable component before a successful attack can be expected. For example, a successful attack may require an attacker to: gather knowledge about the environment in which the vulnerable target/component exists; prepare the target environment to improve exploit reliability; or inject themselves into the logical network path between the target and the resource requested by the victim in order to read and/or modify network communications (e.g., a man in the middle attack)." + } + }, + MPR: { + X: { + l: 'Not Defined', + d: "The value assigned to the corresponding Base metric is used." + }, + N: { + l: 'None', + d: "The attacker is unauthorized prior to attack, and therefore does not require any access to settings or files to carry out an attack." + }, + L: { + l: 'Low', + d: "The attacker is authorized with (i.e., requires) privileges that provide basic user capabilities that could normally affect only settings and files owned by a user. Alternatively, an attacker with Low privileges may have the ability to cause an impact only to non-sensitive resources." + }, + H: { + l: 'High', + d: "The attacker is authorized with (i.e., requires) privileges that provide significant (e.g., administrative) control over the vulnerable component that could affect component-wide settings and files." + } + }, + MUI: { + X: { + l: 'Not Defined', + d: "The value assigned to the corresponding Base metric is used." + }, + N: { + l: 'None', + d: "The vulnerable system can be exploited without any interaction from any user." + }, + R: { + l: 'Required', + d: "Successful exploitation of this vulnerability requires a user to take some action before the vulnerability can be exploited." + } + }, + MS: { + X: { + l: 'Not Defined', + d: "The value assigned to the corresponding Base metric is used." + }, + U: { + l: 'Unchanged', + d: "An exploited vulnerability can only affect resources managed by the same security authority. In this case, the vulnerable component and the impacted component are either the same, or both are managed by the same security authority." + }, + C: { + l: 'Changed', + d: "An exploited vulnerability can affect resources beyond the security scope managed by the security authority of the vulnerable component. In this case, the vulnerable component and the impacted component are different and managed by different security authorities." + } + }, + MC: { + X: { + l: 'Not Defined', + d: "The value assigned to the corresponding Base metric is used." + }, + N: { + l: 'None', + d: "There is no loss of confidentiality within the impacted component." + }, + L: { + l: 'Low', + d: "There is some loss of confidentiality. Access to some restricted information is obtained, but the attacker does not have control over what information is obtained, or the amount or kind of loss is limited. The information disclosure does not cause a direct, serious loss to the impacted component." + }, + H: { + l: 'High', + d: "There is total loss of confidentiality, resulting in all resources within the impacted component being divulged to the attacker. Alternatively, access to only some restricted information is obtained, but the disclosed information presents a direct, serious impact." + } + }, + MI: { + X: { + l: 'Not Defined', + d: "The value assigned to the corresponding Base metric is used." + }, + N: { + l: 'None', + d: "There is no loss of integrity within the impacted component." + }, + L: { + l: 'Low', + d: "Modification of data is possible, but the attacker does not have control over the consequence of a modification, or the amount of modification is limited. The data modification does not have a direct, serious impact on the impacted component." + }, + H: { + l: 'High', + d: "There is a total loss of integrity, or a complete loss of protection. For example, the attacker is able to modify any/all files protected by the impacted component. Alternatively, only some files can be modified, but malicious modification would present a direct, serious consequence to the impacted component." + } + }, + MA: { + X: { + l: 'Not Defined', + d: "The value assigned to the corresponding Base metric is used." + }, + N: { + l: 'None', + d: "There is no impact to availability within the impacted component." + }, + L: { + l: 'Low', + d: "Performance is reduced or there are interruptions in resource availability. Even if repeated exploitation of the vulnerability is possible, the attacker does not have the ability to completely deny service to legitimate users. The resources in the impacted component are either partially available all of the time, or fully available only some of the time, but overall there is no direct, serious consequence to the impacted component." + }, + H: { + l: 'High', + d: "There is total loss of availability, resulting in the attacker being able to fully deny access to resources in the impacted component; this loss is either sustained (while the attacker continues to deliver the attack) or persistent (the condition persists even after the attack has completed). Alternatively, the attacker has the ability to deny some availability, but the loss of availability presents a direct, serious consequence to the impacted component (e.g., the attacker cannot disrupt existing connections, but can prevent new connections; the attacker can repeatedly exploit a vulnerability that, in each instance of a successful attack, leaks a only small amount of memory, but after repeated exploitation causes a service to become completely unavailable)." + } + } + }; + + // Base Group Values + bgv = { AV: 'NALP', AC: 'LH', PR: 'NLH', @@ -191,237 +495,269 @@ var CVSS = function (id, options) { I: 'HLN', A: 'HLN' }; - this.bmoReg = { - AV: 'NALP', - AC: 'LH', - C: 'C', - I: 'C', - A: 'C' + + // Temporal Group Values + tgv = { + //...bgv, + E: 'XUPFH', + RL: 'XOTWU', + RC: 'XURC' + }; + + // Environmental Group Values + egv = { + //...tgv, + CR: 'XLMH', + IR: 'XLMH', + AR: 'XLMH', + MAV: 'XNALP', + MAC: 'XLH', + MPR: 'XNLH', + MUI: 'XNR', + MS: 'XUC', + MC: 'XNLH', + MI: 'XNLH', + MA: 'XNLH' }; - var s, f, dl, g, dd, l; - this.el = document.getElementById(id); - this.el.appendChild(s = e('style')); - s.innerHTML = ''; - this.el.appendChild(f = e('form')); - f.className = 'cvssjs'; - this.calc = f; - for (g in this.bg) { - f.appendChild(dl = e('dl')); - dl.setAttribute('class', g); - var dt = e('dt'); - dt.innerHTML = this.bg[g]; - dl.appendChild(dt); - for (s in this.bm[g]) { - dd = e('dd'); - dl.appendChild(dd); - var inp = e('input'); - inp.setAttribute('name', g); - inp.setAttribute('value', s); - inp.setAttribute('id', id + g + s); - inp.setAttribute('class', g + s); - //inp.setAttribute('ontouchstart', ''); - inp.setAttribute('type', 'radio'); - this.bme[g + s] = inp; - var me = this; - inp.onchange = function () { - me.setMetric(this); + + // All Group Values + agv = { + ...bgv, + ...tgv, + ...egv + }; + + // Severity Ratings + severityRatings = [{ + name: "None", + bottom: 0.0, + top: 0.0 + }, { + name: "Low", + bottom: 0.1, + top: 3.9 + }, { + name: "Medium", + bottom: 4.0, + top: 6.9 + }, { + name: "High", + bottom: 7.0, + top: 8.9 + }, { + name: "Critical", + bottom: 9.0, + top: 10.0 + }]; + + // Reference for all cvss board inputs + this.metricInputs = {}; + + // Find where to draw the cvss board + this.rootElement = document.getElementById(id); + + // Create Form inside root element + this.cvssform = createTag('form'); + this.cvssform.className = 'cvssjs'; + this.rootElement.appendChild(this.cvssform); + + // Create base metrics board + this.createDOMTags(id, options, allGroup.base, baseMetrics); + this.cvssform.appendChild(createTag('hr')); + // Create CVSS String & Score + this.locateScoreBox(this.cvssform, options); + // Values to compose the vector + this.vectorMetrics = { ...baseMetrics }; + + if (showGroups > 1) { + this.vectorMetrics = { ...this.vectorMetrics, ...tempMetrics, ...envMetrics }; + // Create temp metrics board + this.createDOMTags(id, options, allGroup.temp, tempMetrics); + this.cvssform.appendChild(createTag('hr')); + // Create env metrics board + this.createDOMTags(id, options, allGroup.env, envMetrics); + } +} + +function createTag(tag) { + return document.createElement(tag); +}; + +/** + * Create a description list for each of the metrics passed. + * + * @param {ID for the DOM element from which to hung metrics elements} id + * @param {Options to customize events} options + * @param {Metrics to display} groups + */ +CVSS.prototype.createDOMTags = function(id, options, groups, metrics) { + for (group in groups) { + // Create description list tag for each group of metrics + const groupTag = createTag('dl'); + groupTag.setAttribute('class', group); + this.cvssform.appendChild(groupTag); + // Set a description term tag as header for the group metrics + const groupHeader = createTag('dt'); + groupHeader.innerHTML = groups[group]; + groupTag.appendChild(groupHeader); + // Create description for each metric + for (metric in metrics[group]) { + const metricTag = createTag('dd'); + groupTag.appendChild(metricTag); + // Add a radio input to each metric + const metricRadio = createTag('input'); + metricRadio.setAttribute('name', group); + metricRadio.setAttribute('value', metric); + metricRadio.setAttribute('id', id + group + metric); + metricRadio.setAttribute('class', group + metric); + metricRadio.setAttribute('type', 'radio'); + // Keep reference of metric input + this.metricInputs[group + metric] = metricRadio; + // Set onChange event for metric input + const cvssInstance = this; + metricRadio.onchange = function () { + cvssInstance.setMetric(this); }; - dd.appendChild(inp); - l = e('label'); - dd.appendChild(l); - l.setAttribute('for', id + g + s); - l.appendChild(e('i')).setAttribute('class', g + s); - l.appendChild(document.createTextNode(this.bm[g][s].l + ' ')); - dd.appendChild(e('small')).innerHTML = this.bm[g][s].d; + // Append input to metric tag + metricTag.appendChild(metricRadio); + // Create long description tag for this metric + const l = createTag('label'); + l.setAttribute('for', id + group + metric); + l.appendChild(createTag('i')).setAttribute('class', group + metric); + l.appendChild(document.createTextNode(metrics[group][metric].l + ' ')); + // Append the description + metricTag.appendChild(l); + // Finally, set metric title + metricTag.appendChild(createTag('small')).innerHTML = metrics[group][metric].d; } } - //f.appendChild(e('hr')); - f.appendChild(dl = e('dl')); - dl.innerHTML = '
Severity⋅Score⋅Vector
'; - dd = e('dd'); - dl.appendChild(dd); - l = dd.appendChild(e('label')); - l.className = 'results'; - l.appendChild(this.severity = e('span')); - this.severity.className = 'severity'; - l.appendChild(this.score = e('span')); - this.score.className = 'score'; - l.appendChild(document.createTextNode(' ')); - l.appendChild(this.vector = e('a')); - this.vector.className = 'vector'; - this.vector.innerHTML = 'CVSS:3.1/AV:_/AC:_/PR:_/UI:_/S:_/C:_/I:_/A:_'; +} +/** + * Creates a box with the resulting cvss string and score + * + * @param {reference to cvss form} f + * @param {options to customize events} options + */ +CVSS.prototype.locateScoreBox = function(f, options) { + this.vector = $("#cvssresults a.vector"); + + // Add onSubmit event if passed as argument if (options.onsubmit) { - f.appendChild(e('hr')); - this.submitButton = f.appendChild(e('input')); + f.appendChild(createTag('hr')); + this.submitButton = f.appendChild(createTag('input')); this.submitButton.setAttribute('type', 'submit'); this.submitButton.onclick = options.onsubmit; } -}; +} -CVSS.prototype.severityRatings = [{ - name: "None", - bottom: 0.0, - top: 0.0 -}, { - name: "Low", - bottom: 0.1, - top: 3.9 -}, { - name: "Medium", - bottom: 4.0, - top: 6.9 -}, { - name: "High", - bottom: 7.0, - top: 8.9 -}, { - name: "Critical", - bottom: 9.0, - top: 10.0 -}]; - -CVSS.prototype.severityRating = function (score) { - var i; - var severityRatingLength = this.severityRatings.length; - for (i = 0; i < severityRatingLength; i++) { - if (score >= this.severityRatings[i].bottom && score <= this.severityRatings[i].top) { - return this.severityRatings[i]; - } - } - return { - name: "?", - bottom: 'Not', - top: 'defined' - }; -}; +CVSS.prototype.set = function(vec) { + let newVec = 'CVSS:3.1'; + + for (const m in baseMetrics) newVec = this.formatVector(vec, m, newVec, agv, true); + // Do not add temporal or environmental metrics if not present + for (const m in tempMetrics) newVec = this.formatVector(vec, m, newVec, agv, false); + for (const m in envMetrics) newVec = this.formatVector(vec, m, newVec, agv, false); -CVSS.prototype.valueofradio = function(e) { - for(var i = 0; i < e.length; i++) { - if (e[i].checked) { - return e[i].value; - } - } - return null; + this.update(newVec); }; -CVSS.prototype.calculate = function () { - var cvssVersion = "3.1"; - var exploitabilityCoefficient = 8.22; - var scopeCoefficient = 1.08; - - // Define associative arrays mapping each metric value to the constant used in the CVSS scoring formula. - var Weight = { - AV: { - N: 0.85, - A: 0.62, - L: 0.55, - P: 0.2 - }, - AC: { - H: 0.44, - L: 0.77 - }, - PR: { - U: { - N: 0.85, - L: 0.62, - H: 0.27 - }, - // These values are used if Scope is Unchanged - C: { - N: 0.85, - L: 0.68, - H: 0.5 +CVSS.prototype.formatVector = function(vec, m, newVec, values, addIfMissing) { + let sep = '/'; + let match = (new RegExp('\\b(' + m + ':[' + values[m] + '])')).exec(vec); + if (match !== null) { + const check = match[0].replace(':', ''); + this.metricInputs[check].checked = true; + newVec = newVec + sep + match[0]; + } else if ((m in {C:'', I:'', A:''}) && (match = (new RegExp('\\b(' + m + ':C)')).exec(vec)) !== null) { + // compatibility with v2 only for CIA:C + this.metricInputs[m + 'H'].checked = true; + newVec = newVec + sep + m + ':H'; + } else { + if (addIfMissing) { + newVec = newVec + sep + m + ':_'; + } + for (const j in this.vectorMetrics[m]) { + // Metrics from the temp and/or env groups are not in the base vector + if (this.metricInputs[m + j].checked) { + newVec = newVec + sep + m + ":" + this.metricInputs[m + j].value; + } else { + this.metricInputs[m + j].checked = false; } - }, - // These values are used if Scope is Changed - UI: { - N: 0.85, - R: 0.62 - }, - S: { - U: 6.42, - C: 7.52 - }, - C: { - N: 0, - L: 0.22, - H: 0.56 - }, - I: { - N: 0, - L: 0.22, - H: 0.56 - }, - A: { - N: 0, - L: 0.22, - H: 0.56 } - // C, I and A have the same weights + } + return newVec +} - }; +/** + * Updates the results box. + * + * @param {CVSS String} newVec + */ +CVSS.prototype.update = function(newVec) { + this.vector.text(newVec); + var s31 = CVSS31.calculateCVSSFromMetrics( + this.valueofradio(this.cvssform.elements["AV"]), + this.valueofradio(this.cvssform.elements["AC"]), + this.valueofradio(this.cvssform.elements["PR"]), + this.valueofradio(this.cvssform.elements["UI"]), + this.valueofradio(this.cvssform.elements["S"]), + this.valueofradio(this.cvssform.elements["C"]), + this.valueofradio(this.cvssform.elements["I"]), + this.valueofradio(this.cvssform.elements["A"]), + this.valueofradio(this.cvssform.elements["E"]), + this.valueofradio(this.cvssform.elements["RL"]), + this.valueofradio(this.cvssform.elements["RC"]), + this.valueofradio(this.cvssform.elements["CR"]), + this.valueofradio(this.cvssform.elements["IR"]), + this.valueofradio(this.cvssform.elements["AR"]), + this.valueofradio(this.cvssform.elements["MAV"]), + this.valueofradio(this.cvssform.elements["MAC"]), + this.valueofradio(this.cvssform.elements["MPR"]), + this.valueofradio(this.cvssform.elements["MUI"]), + this.valueofradio(this.cvssform.elements["MS"]), + this.valueofradio(this.cvssform.elements["MC"]), + this.valueofradio(this.cvssform.elements["MI"]), + this.valueofradio(this.cvssform.elements["MA"])); + + $("#cvssresults .base-results span.score").text(s31.baseMetricScore); + $("#cvssresults .temp-results span.score").text(s31.temporalMetricScore); + $("#cvssresults .env-results span.score").text(s31.environmentalMetricScore); - var p; - var val = {}, metricWeight = {}; - try { - for (p in this.bg) { - val[p] = this.valueofradio(this.calc.elements[p]); - if (typeof val[p] === "undefined" || val[p] === null) { - return "?"; - } - metricWeight[p] = Weight[p][val[p]]; - } - } catch (err) { - return err; // TODO: need to catch and return sensible error value & do a better job of specifying *which* parm is at fault. + if (s31.baseSeverity !== undefined && s31.baseSeverity !== null) { + $("#cvssresults .base-results span.severity") + .attr("class", s31.baseSeverity + " severity") + .text(s31.baseSeverity); } - metricWeight.PR = Weight.PR[val.S][val.PR]; - // - // CALCULATE THE CVSS BASE SCORE - // - var roundUp1 = function Roundup(input) { - var int_input = Math.round(input * 100000); - if (int_input % 10000 === 0) { - return int_input / 100000 - } else { - return (Math.floor(int_input / 10000) + 1) / 10 - } - }; - try { - var baseScore, impactSubScore, impact, exploitability; - var impactSubScoreMultiplier = (1 - ((1 - metricWeight.C) * (1 - metricWeight.I) * (1 - metricWeight.A))); - if (val.S === 'U') { - impactSubScore = metricWeight.S * impactSubScoreMultiplier; - } else { - impactSubScore = metricWeight.S * (impactSubScoreMultiplier - 0.029) - 3.25 * Math.pow(impactSubScoreMultiplier - 0.02, 15); + if (s31.baseSeverity !== undefined && s31.baseSeverity !== null) { + $("#cvssresults .temp-results span.severity") + .attr("class", s31.temporalSeverity + " severity") + .text(s31.temporalSeverity); } - var exploitabalitySubScore = exploitabilityCoefficient * metricWeight.AV * metricWeight.AC * metricWeight.PR * metricWeight.UI; - if (impactSubScore <= 0) { - baseScore = 0; - } else { - if (val.S === 'U') { - baseScore = roundUp1(Math.min((exploitabalitySubScore + impactSubScore), 10)); - } else { - baseScore = roundUp1(Math.min((exploitabalitySubScore + impactSubScore) * scopeCoefficient, 10)); - } + if (s31.baseSeverity !== undefined && s31.baseSeverity !== null) { + $("#cvssresults .env-results span.severity") + .attr("class", s31.environmentalSeverity + " severity") + .text(s31.environmentalSeverity); } - return baseScore.toFixed(1); - } catch (err) { - return err; - } -}; + $("#cvssresults .base-results a.vector").text(s31.vectorString); -CVSS.prototype.get = function() { - return { - score: this.score.innerHTML, - vector: this.vector.innerHTML - }; + /*const rating = this.severityRating(s); + this.severity.className = rating.name + ' severity'; + this.severity.innerHTML = rating.name + '' + rating.bottom + ' - ' + rating.top + ''; + this.severity.title = rating.bottom + ' - ' + rating.top;*/ + if (this.options !== undefined && this.options.onchange !== undefined) { + this.options.onchange(); + } }; +/** + * Replaces metric's value in the vector string + * + * @param {New value for a metric} a + */ CVSS.prototype.setMetric = function(a) { - var vectorString = this.vector.innerHTML; + var vectorString = this.vector.text(); if (/AV:.\/AC:.\/PR:.\/UI:.\/S:.\/C:.\/I:.\/A:./.test(vectorString)) {} else { vectorString = 'AV:_/AC:_/PR:_/UI:_/S:_/C:_/I:_/A:_'; } @@ -430,39 +766,23 @@ CVSS.prototype.setMetric = function(a) { this.set(newVec); }; -CVSS.prototype.set = function(vec) { - var newVec = 'CVSS:3.1/'; - var sep = ''; - for (var m in this.bm) { - var match = (new RegExp('\\b(' + m + ':[' + this.bmgReg[m] + '])')).exec(vec); - if (match !== null) { - var check = match[0].replace(':', ''); - this.bme[check].checked = true; - newVec = newVec + sep + match[0]; - } else if ((m in {C:'', I:'', A:''}) && (match = (new RegExp('\\b(' + m + ':C)')).exec(vec)) !== null) { - // compatibility with v2 only for CIA:C - this.bme[m + 'H'].checked = true; - newVec = newVec + sep + m + ':H'; - } else { - newVec = newVec + sep + m + ':_'; - for (var j in this.bm[m]) { - this.bme[m + j].checked = false; - } +/** + * Checks which metric value is selected from a list of radio inputs. + * + * @param {List of a metric's values radio inputs} e + */ +CVSS.prototype.valueofradio = function(e) { + for(var i = 0; i < e.length; i++) { + if (e[i].checked) { + return e[i].value; } - sep = '/'; } - this.update(newVec); + return null; }; -CVSS.prototype.update = function(newVec) { - this.vector.innerHTML = newVec; - var s = this.calculate(); - this.score.innerHTML = s; - var rating = this.severityRating(s); - this.severity.className = rating.name + ' severity'; - this.severity.innerHTML = rating.name + '' + rating.bottom + ' - ' + rating.top + ''; - this.severity.title = rating.bottom + ' - ' + rating.top; - if (this.options !== undefined && this.options.onchange !== undefined) { - this.options.onchange(); - } +CVSS.prototype.get = function() { + return { + score: $("#cvssresults .base-results span.score").text(), + vector: this.vector.text() + }; }; \ No newline at end of file diff --git a/static/js/cvsscalc31.js b/static/js/cvsscalc31.js new file mode 100644 index 0000000..20a5c8f --- /dev/null +++ b/static/js/cvsscalc31.js @@ -0,0 +1,753 @@ +/* Copyright (c) 2019, FIRST.ORG, INC. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* This JavaScript contains two main functions. Both take CVSS metric values and calculate CVSS scores for Base, + * Temporal and Environmental metric groups, their associated severity ratings, and an overall Vector String. + * + * Use CVSS31.calculateCVSSFromMetrics if you wish to pass metric values as individual parameters. + * Use CVSS31.calculateCVSSFromVector if you wish to pass metric values as a single Vector String. + * + * Changelog + * + * 2019-06-01 Darius Wiles Updates for CVSS version 3.1: + * + * 1) The CVSS31.roundUp1 function now performs rounding using integer arithmetic to + * eliminate problems caused by tiny errors introduced during JavaScript math + * operations. Thanks to Stanislav Kontar of Red Hat for suggesting and testing + * various implementations. + * + * 2) Environmental formulas changed to prevent the Environmental Score decreasing when + * the value of an Environmental metric is raised. The problem affected a small + * percentage of CVSS v3.0 metrics. The change is to the modifiedImpact + * formula, but only affects scores where the Modified Scope is Changed (or the + * Scope is Changed if Modified Scope is Not Defined). + * + * 3) The JavaScript object containing everything in this file has been renamed from + * "CVSS" to "CVSS31" to allow both objects to be included without causing a + * naming conflict. + * + * 4) Variable names and code order have changed to more closely reflect the formulas + * in the CVSS v3.1 Specification Document. + * + * 5) A successful call to calculateCVSSFromMetrics now returns sub-formula values. + * + * Note that some sets of metrics will produce different scores between CVSS v3.0 and + * v3.1 as a result of changes 1 and 2. See the explanation of changes between these + * two standards in the CVSS v3.1 User Guide for more details. + * + * 2018-02-15 Darius Wiles Added a missing pair of parentheses in the Environmental score, specifically + * in the code setting envScore in the main clause (not the else clause). It was changed + * from "min (...), 10" to "min ((...), 10)". This correction does not alter any final + * Environmental scores. + * + * 2015-08-04 Darius Wiles Added CVSS.generateXMLFromMetrics and CVSS.generateXMLFromVector functions to return + * XML string representations of: a set of metric values; or a Vector String respectively. + * Moved all constants and functions to an object named "CVSS" to + * reduce the chance of conflicts in global variables when this file is combined with + * other JavaScript code. This will break all existing code that uses this file until + * the string "CVSS." is prepended to all references. The "Exploitability" metric has been + * renamed "Exploit Code Maturity" in the specification, so the same change has been made + * in the code in this file. + * + * 2015-04-24 Darius Wiles Environmental formula modified to eliminate undesirable behavior caused by subtle + * differences in rounding between Temporal and Environmental formulas that often + * caused the latter to be 0.1 lower than than the former when all Environmental + * metrics are "Not defined". Also added a RoundUp1 function to simplify formulas. + * + * 2015-04-09 Darius Wiles Added calculateCVSSFromVector function, license information, cleaned up code and improved + * comments. + * + * 2014-12-12 Darius Wiles Initial release for CVSS 3.0 Preview 2. + */ + +// Constants used in the formula. They are not declared as "const" to avoid problems in older browsers. + +var CVSS31 = {}; + +CVSS31.CVSSVersionIdentifier = "CVSS:3.1"; +CVSS31.exploitabilityCoefficient = 8.22; +CVSS31.scopeCoefficient = 1.08; + +// A regular expression to validate that a CVSS 3.1 vector string is well formed. It checks metrics and metric +// values. It does not check that a metric is specified more than once and it does not check that all base +// metrics are present. These checks need to be performed separately. + +CVSS31.vectorStringRegex_31 = /^CVSS:3\.1\/((AV:[NALP]|AC:[LH]|PR:[UNLH]|UI:[NR]|S:[UC]|[CIA]:[NLH]|E:[XUPFH]|RL:[XOTWU]|RC:[XURC]|[CIA]R:[XLMH]|MAV:[XNALP]|MAC:[XLH]|MPR:[XUNLH]|MUI:[XNR]|MS:[XUC]|M[CIA]:[XNLH])\/)*(AV:[NALP]|AC:[LH]|PR:[UNLH]|UI:[NR]|S:[UC]|[CIA]:[NLH]|E:[XUPFH]|RL:[XOTWU]|RC:[XURC]|[CIA]R:[XLMH]|MAV:[XNALP]|MAC:[XLH]|MPR:[XUNLH]|MUI:[XNR]|MS:[XUC]|M[CIA]:[XNLH])$/; + + +// Associative arrays mapping each metric value to the constant defined in the CVSS scoring formula in the CVSS v3.1 +// specification. + +CVSS31.Weight = { + AV: { N: 0.85, A: 0.62, L: 0.55, P: 0.2}, + AC: { H: 0.44, L: 0.77}, + PR: { U: {N: 0.85, L: 0.62, H: 0.27}, // These values are used if Scope is Unchanged + C: {N: 0.85, L: 0.68, H: 0.5}}, // These values are used if Scope is Changed + UI: { N: 0.85, R: 0.62}, + S: { U: 6.42, C: 7.52}, // Note: not defined as constants in specification + CIA: { N: 0, L: 0.22, H: 0.56}, // C, I and A have the same weights + + E: { X: 1, U: 0.91, P: 0.94, F: 0.97, H: 1}, + RL: { X: 1, O: 0.95, T: 0.96, W: 0.97, U: 1}, + RC: { X: 1, U: 0.92, R: 0.96, C: 1}, + + CIAR: { X: 1, L: 0.5, M: 1, H: 1.5} // CR, IR and AR have the same weights +}; + + +// Severity rating bands, as defined in the CVSS v3.1 specification. + +CVSS31.severityRatings = [ { name: "None", bottom: 0.0, top: 0.0}, + { name: "Low", bottom: 0.1, top: 3.9}, + { name: "Medium", bottom: 4.0, top: 6.9}, + { name: "High", bottom: 7.0, top: 8.9}, + { name: "Critical", bottom: 9.0, top: 10.0} ]; + + + + +/* ** CVSS31.calculateCVSSFromMetrics ** + * + * Takes Base, Temporal and Environmental metric values as individual parameters. Their values are in the short format + * defined in the CVSS v3.1 standard definition of the Vector String. For example, the AttackComplexity parameter + * should be either "H" or "L". + * + * Returns Base, Temporal and Environmental scores, severity ratings, and an overall Vector String. All Base metrics + * are required to generate this output. All Temporal and Environmental metric values are optional. Any that are not + * passed default to "X" ("Not Defined"). + * + * The output is an object which always has a property named "success". + * + * If no errors are encountered, success is Boolean "true", and the following other properties are defined containing + * scores, severities and a vector string: + * baseMetricScore, baseSeverity, + * temporalMetricScore, temporalSeverity, + * environmentalMetricScore, environmentalSeverity, + * vectorString + * + * The following properties are also defined, and contain sub-formula values: + * baseISS, baseImpact, baseExploitability, + * environmentalMISS, environmentalModifiedImpact, environmentalModifiedExploitability + * + * + * If errors are encountered, success is Boolean "false", and the following other properties are defined: + * errorType - a string indicating the error. Either: + * "MissingBaseMetric", if at least one Base metric has not been defined; or + * "UnknownMetricValue", if at least one metric value is invalid. + * errorMetrics - an array of strings representing the metrics at fault. The strings are abbreviated versions of the + * metrics, as defined in the CVSS v3.1 standard definition of the Vector String. + */ +CVSS31.calculateCVSSFromMetrics = function ( + AttackVector, AttackComplexity, PrivilegesRequired, UserInteraction, Scope, Confidentiality, Integrity, Availability, + ExploitCodeMaturity, RemediationLevel, ReportConfidence, + ConfidentialityRequirement, IntegrityRequirement, AvailabilityRequirement, + ModifiedAttackVector, ModifiedAttackComplexity, ModifiedPrivilegesRequired, ModifiedUserInteraction, ModifiedScope, + ModifiedConfidentiality, ModifiedIntegrity, ModifiedAvailability) { + + // If input validation fails, this array is populated with strings indicating which metrics failed validation. + var badMetrics = []; + + // ENSURE ALL BASE METRICS ARE DEFINED + // + // We need values for all Base Score metrics to calculate scores. + // If any Base Score parameters are undefined, create an array of missing metrics and return it with an error. + + if (typeof AttackVector === "undefined" || AttackVector === "") { badMetrics.push("AV"); } + if (typeof AttackComplexity === "undefined" || AttackComplexity === "") { badMetrics.push("AC"); } + if (typeof PrivilegesRequired === "undefined" || PrivilegesRequired === "") { badMetrics.push("PR"); } + if (typeof UserInteraction === "undefined" || UserInteraction === "") { badMetrics.push("UI"); } + if (typeof Scope === "undefined" || Scope === "") { badMetrics.push("S"); } + if (typeof Confidentiality === "undefined" || Confidentiality === "") { badMetrics.push("C"); } + if (typeof Integrity === "undefined" || Integrity === "") { badMetrics.push("I"); } + if (typeof Availability === "undefined" || Availability === "") { badMetrics.push("A"); } + + if (badMetrics.length > 0) { + return { success: false, errorType: "MissingBaseMetric", errorMetrics: badMetrics }; + } + + + // STORE THE METRIC VALUES THAT WERE PASSED AS PARAMETERS + // + // Temporal and Environmental metrics are optional, so set them to "X" ("Not Defined") if no value was passed. + + var AV = AttackVector; + var AC = AttackComplexity; + var PR = PrivilegesRequired; + var UI = UserInteraction; + var S = Scope; + var C = Confidentiality; + var I = Integrity; + var A = Availability; + + var E = ExploitCodeMaturity || "X"; + var RL = RemediationLevel || "X"; + var RC = ReportConfidence || "X"; + + var CR = ConfidentialityRequirement || "X"; + var IR = IntegrityRequirement || "X"; + var AR = AvailabilityRequirement || "X"; + var MAV = ModifiedAttackVector || "X"; + var MAC = ModifiedAttackComplexity || "X"; + var MPR = ModifiedPrivilegesRequired || "X"; + var MUI = ModifiedUserInteraction || "X"; + var MS = ModifiedScope || "X"; + var MC = ModifiedConfidentiality || "X"; + var MI = ModifiedIntegrity || "X"; + var MA = ModifiedAvailability || "X"; + + + // CHECK VALIDITY OF METRIC VALUES + // + // Use the Weight object to ensure that, for every metric, the metric value passed is valid. + // If any invalid values are found, create an array of their metrics and return it with an error. + // + // The Privileges Required (PR) weight depends on Scope, but when checking the validity of PR we must not assume + // that the given value for Scope is valid. We therefore always look at the weights for Unchanged Scope when + // performing this check. The same applies for validation of Modified Privileges Required (MPR). + // + // The Weights object does not contain "X" ("Not Defined") values for Environmental metrics because we replace them + // with their Base metric equivalents later in the function. For example, an MAV of "X" will be replaced with the + // value given for AV. We therefore need to explicitly allow a value of "X" for Environmental metrics. + + if (!CVSS31.Weight.AV.hasOwnProperty(AV)) { badMetrics.push("AV"); } + if (!CVSS31.Weight.AC.hasOwnProperty(AC)) { badMetrics.push("AC"); } + if (!CVSS31.Weight.PR.U.hasOwnProperty(PR)) { badMetrics.push("PR"); } + if (!CVSS31.Weight.UI.hasOwnProperty(UI)) { badMetrics.push("UI"); } + if (!CVSS31.Weight.S.hasOwnProperty(S)) { badMetrics.push("S"); } + if (!CVSS31.Weight.CIA.hasOwnProperty(C)) { badMetrics.push("C"); } + if (!CVSS31.Weight.CIA.hasOwnProperty(I)) { badMetrics.push("I"); } + if (!CVSS31.Weight.CIA.hasOwnProperty(A)) { badMetrics.push("A"); } + + if (!CVSS31.Weight.E.hasOwnProperty(E)) { badMetrics.push("E"); } + if (!CVSS31.Weight.RL.hasOwnProperty(RL)) { badMetrics.push("RL"); } + if (!CVSS31.Weight.RC.hasOwnProperty(RC)) { badMetrics.push("RC"); } + + if (!(CR === "X" || CVSS31.Weight.CIAR.hasOwnProperty(CR))) { badMetrics.push("CR"); } + if (!(IR === "X" || CVSS31.Weight.CIAR.hasOwnProperty(IR))) { badMetrics.push("IR"); } + if (!(AR === "X" || CVSS31.Weight.CIAR.hasOwnProperty(AR))) { badMetrics.push("AR"); } + if (!(MAV === "X" || CVSS31.Weight.AV.hasOwnProperty(MAV))) { badMetrics.push("MAV"); } + if (!(MAC === "X" || CVSS31.Weight.AC.hasOwnProperty(MAC))) { badMetrics.push("MAC"); } + if (!(MPR === "X" || CVSS31.Weight.PR.U.hasOwnProperty(MPR))) { badMetrics.push("MPR"); } + if (!(MUI === "X" || CVSS31.Weight.UI.hasOwnProperty(MUI))) { badMetrics.push("MUI"); } + if (!(MS === "X" || CVSS31.Weight.S.hasOwnProperty(MS))) { badMetrics.push("MS"); } + if (!(MC === "X" || CVSS31.Weight.CIA.hasOwnProperty(MC))) { badMetrics.push("MC"); } + if (!(MI === "X" || CVSS31.Weight.CIA.hasOwnProperty(MI))) { badMetrics.push("MI"); } + if (!(MA === "X" || CVSS31.Weight.CIA.hasOwnProperty(MA))) { badMetrics.push("MA"); } + + if (badMetrics.length > 0) { + return { success: false, errorType: "UnknownMetricValue", errorMetrics: badMetrics }; + } + + + + // GATHER WEIGHTS FOR ALL METRICS + + var metricWeightAV = CVSS31.Weight.AV [AV]; + var metricWeightAC = CVSS31.Weight.AC [AC]; + var metricWeightPR = CVSS31.Weight.PR [S][PR]; // PR depends on the value of Scope (S). + var metricWeightUI = CVSS31.Weight.UI [UI]; + var metricWeightS = CVSS31.Weight.S [S]; + var metricWeightC = CVSS31.Weight.CIA [C]; + var metricWeightI = CVSS31.Weight.CIA [I]; + var metricWeightA = CVSS31.Weight.CIA [A]; + + var metricWeightE = CVSS31.Weight.E [E]; + var metricWeightRL = CVSS31.Weight.RL [RL]; + var metricWeightRC = CVSS31.Weight.RC [RC]; + + // For metrics that are modified versions of Base Score metrics, e.g. Modified Attack Vector, use the value of + // the Base Score metric if the modified version value is "X" ("Not Defined"). + var metricWeightCR = CVSS31.Weight.CIAR [CR]; + var metricWeightIR = CVSS31.Weight.CIAR [IR]; + var metricWeightAR = CVSS31.Weight.CIAR [AR]; + var metricWeightMAV = CVSS31.Weight.AV [MAV !== "X" ? MAV : AV]; + var metricWeightMAC = CVSS31.Weight.AC [MAC !== "X" ? MAC : AC]; + var metricWeightMPR = CVSS31.Weight.PR [MS !== "X" ? MS : S] [MPR !== "X" ? MPR : PR]; // Depends on MS. + var metricWeightMUI = CVSS31.Weight.UI [MUI !== "X" ? MUI : UI]; + var metricWeightMS = CVSS31.Weight.S [MS !== "X" ? MS : S]; + var metricWeightMC = CVSS31.Weight.CIA [MC !== "X" ? MC : C]; + var metricWeightMI = CVSS31.Weight.CIA [MI !== "X" ? MI : I]; + var metricWeightMA = CVSS31.Weight.CIA [MA !== "X" ? MA : A]; + + + + // CALCULATE THE CVSS BASE SCORE + + var iss; /* Impact Sub-Score */ + var impact; + var exploitability; + var baseScore; + + iss = (1 - ((1 - metricWeightC) * (1 - metricWeightI) * (1 - metricWeightA))); + + if (S === 'U') { + impact = metricWeightS * iss; + } else { + impact = metricWeightS * (iss - 0.029) - 3.25 * Math.pow(iss - 0.02, 15); + } + + exploitability = CVSS31.exploitabilityCoefficient * metricWeightAV * metricWeightAC * metricWeightPR * metricWeightUI; + + if (impact <= 0) { + baseScore = 0; + } else { + if (S === 'U') { + baseScore = CVSS31.roundUp1(Math.min((exploitability + impact), 10)); + } else { + baseScore = CVSS31.roundUp1(Math.min(CVSS31.scopeCoefficient * (exploitability + impact), 10)); + } + } + + + // CALCULATE THE CVSS TEMPORAL SCORE + + var temporalScore = CVSS31.roundUp1(baseScore * metricWeightE * metricWeightRL * metricWeightRC); + + + // CALCULATE THE CVSS ENVIRONMENTAL SCORE + // + // - modifiedExploitability recalculates the Base Score Exploitability sub-score using any modified values from the + // Environmental metrics group in place of the values specified in the Base Score, if any have been defined. + // - modifiedImpact recalculates the Base Score Impact sub-score using any modified values from the + // Environmental metrics group in place of the values specified in the Base Score, and any additional weightings + // given in the Environmental metrics group. + + var miss; /* Modified Impact Sub-Score */ + var modifiedImpact; + var envScore; + var modifiedExploitability; + + miss = Math.min (1 - + ( (1 - metricWeightMC * metricWeightCR) * + (1 - metricWeightMI * metricWeightIR) * + (1 - metricWeightMA * metricWeightAR)), 0.915); + + if (MS === "U" || + (MS === "X" && S === "U")) { + modifiedImpact = metricWeightMS * miss; + } else { + modifiedImpact = metricWeightMS * (miss - 0.029) - 3.25 * Math.pow(miss * 0.9731 - 0.02, 13); + } + + modifiedExploitability = CVSS31.exploitabilityCoefficient * metricWeightMAV * metricWeightMAC * metricWeightMPR * metricWeightMUI; + + if (modifiedImpact <= 0) { + envScore = 0; + } else if (MS === "U" || (MS === "X" && S === "U")) { + envScore = CVSS31.roundUp1(CVSS31.roundUp1(Math.min((modifiedImpact + modifiedExploitability), 10)) * + metricWeightE * metricWeightRL * metricWeightRC); + } else { + envScore = CVSS31.roundUp1(CVSS31.roundUp1(Math.min(CVSS31.scopeCoefficient * (modifiedImpact + modifiedExploitability), 10)) * + metricWeightE * metricWeightRL * metricWeightRC); + } + + + // CONSTRUCT THE VECTOR STRING + + var vectorString = + CVSS31.CVSSVersionIdentifier + + "/AV:" + AV + + "/AC:" + AC + + "/PR:" + PR + + "/UI:" + UI + + "/S:" + S + + "/C:" + C + + "/I:" + I + + "/A:" + A; + + if (E !== "X") {vectorString = vectorString + "/E:" + E;} + if (RL !== "X") {vectorString = vectorString + "/RL:" + RL;} + if (RC !== "X") {vectorString = vectorString + "/RC:" + RC;} + + if (CR !== "X") {vectorString = vectorString + "/CR:" + CR;} + if (IR !== "X") {vectorString = vectorString + "/IR:" + IR;} + if (AR !== "X") {vectorString = vectorString + "/AR:" + AR;} + if (MAV !== "X") {vectorString = vectorString + "/MAV:" + MAV;} + if (MAC !== "X") {vectorString = vectorString + "/MAC:" + MAC;} + if (MPR !== "X") {vectorString = vectorString + "/MPR:" + MPR;} + if (MUI !== "X") {vectorString = vectorString + "/MUI:" + MUI;} + if (MS !== "X") {vectorString = vectorString + "/MS:" + MS;} + if (MC !== "X") {vectorString = vectorString + "/MC:" + MC;} + if (MI !== "X") {vectorString = vectorString + "/MI:" + MI;} + if (MA !== "X") {vectorString = vectorString + "/MA:" + MA;} + + + // Return an object containing the scores for all three metric groups, and an overall vector string. + // Sub-formula values are also included. + + return { + success: true, + + baseMetricScore: baseScore.toFixed(1), + baseSeverity: CVSS31.severityRating( baseScore.toFixed(1) ), + baseISS: iss, + baseImpact: impact, + baseExploitability: exploitability, + + temporalMetricScore: temporalScore.toFixed(1), + temporalSeverity: CVSS31.severityRating( temporalScore.toFixed(1) ), + + environmentalMetricScore: envScore.toFixed(1), + environmentalSeverity: CVSS31.severityRating( envScore.toFixed(1) ), + environmentalMISS: miss, + environmentalModifiedImpact: modifiedImpact, + environmentalModifiedExploitability: modifiedExploitability, + + vectorString: vectorString + }; +}; + + + + +/* ** CVSS31.calculateCVSSFromVector ** + * + * Takes Base, Temporal and Environmental metric values as a single string in the Vector String format defined + * in the CVSS v3.1 standard definition of the Vector String. + * + * Returns Base, Temporal and Environmental scores, severity ratings, and an overall Vector String. All Base metrics + * are required to generate this output. All Temporal and Environmental metric values are optional. Any that are not + * passed default to "X" ("Not Defined"). + * + * See the comment for the CVSS31.calculateCVSSFromMetrics function for details on the function output. In addition to + * the error conditions listed for that function, this function can also return: + * "MalformedVectorString", if the Vector String passed does not conform to the format in the standard; or + * "MultipleDefinitionsOfMetric", if the Vector String is well formed but defines the same metric (or metrics), + * more than once. + */ +CVSS31.calculateCVSSFromVector = function ( vectorString ) { + + var metricValues = { + AV: undefined, AC: undefined, PR: undefined, UI: undefined, S: undefined, + C: undefined, I: undefined, A: undefined, + E: undefined, RL: undefined, RC: undefined, + CR: undefined, IR: undefined, AR: undefined, + MAV: undefined, MAC: undefined, MPR: undefined, MUI: undefined, MS: undefined, + MC: undefined, MI: undefined, MA: undefined + }; + + // If input validation fails, this array is populated with strings indicating which metrics failed validation. + var badMetrics = []; + + if (!CVSS31.vectorStringRegex_31.test(vectorString)) { + return { success: false, errorType: "MalformedVectorString" }; + } + + var metricNameValue = vectorString.substring(CVSS31.CVSSVersionIdentifier.length).split("/"); + + for (var i in metricNameValue) { + if (metricNameValue.hasOwnProperty(i)) { + + var singleMetric = metricNameValue[i].split(":"); + + if (typeof metricValues[singleMetric[0]] === "undefined") { + metricValues[singleMetric[0]] = singleMetric[1]; + } else { + badMetrics.push(singleMetric[0]); + } + } + } + + if (badMetrics.length > 0) { + return { success: false, errorType: "MultipleDefinitionsOfMetric", errorMetrics: badMetrics }; + } + + return CVSS31.calculateCVSSFromMetrics ( + metricValues.AV, metricValues.AC, metricValues.PR, metricValues.UI, metricValues.S, + metricValues.C, metricValues.I, metricValues.A, + metricValues.E, metricValues.RL, metricValues.RC, + metricValues.CR, metricValues.IR, metricValues.AR, + metricValues.MAV, metricValues.MAC, metricValues.MPR, metricValues.MUI, metricValues.MS, + metricValues.MC, metricValues.MI, metricValues.MA); +}; + + + + +/* ** CVSS31.roundUp1 ** + * + * Rounds up its parameter to 1 decimal place and returns the result. + * + * Standard JavaScript errors thrown when arithmetic operations are performed on non-numbers will be returned if the + * given input is not a number. + * + * Implementation note: Tiny representation errors in floating point numbers makes rounding complex. For example, + * consider calculating Math.ceil((1-0.58)*100) by hand. It can be simplified to Math.ceil(0.42*100), then + * Math.ceil(42), and finally 42. Most JavaScript implementations give 43. The problem is that, on many systems, + * 1-0.58 = 0.42000000000000004, and the tiny error is enough to push ceil up to the next integer. The implementation + * below avoids such problems by performing the rounding using integers. The input is first multiplied by 100,000 + * and rounded to the nearest integer to consider 6 decimal places of accuracy, so 0.000001 results in 0.0, but + * 0.000009 results in 0.1. + * + * A more elegant solution may be possible, but the following gives answers consistent with results from an arbitrary + * precision library. + */ +CVSS31.roundUp1 = function Roundup (input) { + var int_input = Math.round(input * 100000); + + if (int_input % 10000 === 0) { + return int_input / 100000; + } else { + return (Math.floor(int_input / 10000) + 1) / 10; + } +}; + + + +/* ** CVSS31.severityRating ** + * + * Given a CVSS score, returns the name of the severity rating as defined in the CVSS standard. + * The input needs to be a number between 0.0 to 10.0, to one decimal place of precision. + * + * The following error values may be returned instead of a severity rating name: + * NaN (JavaScript "Not a Number") - if the input is not a number. + * undefined - if the input is a number that is not within the range of any defined severity rating. + */ +CVSS31.severityRating = function (score) { + var severityRatingLength = CVSS31.severityRatings.length; + + var validatedScore = Number(score); + + if (isNaN(validatedScore)) { + return validatedScore; + } + + for (var i = 0; i < severityRatingLength; i++) { + if (score >= CVSS31.severityRatings[i].bottom && score <= CVSS31.severityRatings[i].top) { + return CVSS31.severityRatings[i].name; + } + } + + return undefined; +}; + + + +/////////////////////////////////////////////////////////////////////////// +// DATA AND FUNCTIONS FOR CREATING AN XML REPRESENTATION OF A CVSS SCORE // +/////////////////////////////////////////////////////////////////////////// + +// A mapping between abbreviated metric values and the string used in the XML representation. +// For example, a Remediation Level (RL) abbreviated metric value of "W" maps to "WORKAROUND". +// For brevity, every Base metric shares its definition with its equivalent Environmental metric. This is possible +// because the metric values are same between these groups, except that the latter have an additional metric value +// of "NOT_DEFINED". + +CVSS31.XML_MetricNames = { + E: { X: "NOT_DEFINED", U: "UNPROVEN", P: "PROOF_OF_CONCEPT", F: "FUNCTIONAL", H: "HIGH"}, + RL: { X: "NOT_DEFINED", O: "OFFICIAL_FIX", T: "TEMPORARY_FIX", W: "WORKAROUND", U: "UNAVAILABLE"}, + RC: { X: "NOT_DEFINED", U: "UNKNOWN", R: "REASONABLE", C: "CONFIRMED"}, + + CIAR: { X: "NOT_DEFINED", L: "LOW", M: "MEDIUM", H: "HIGH"}, // CR, IR and AR use the same values + MAV: { N: "NETWORK", A: "ADJACENT_NETWORK", L: "LOCAL", P: "PHYSICAL", X: "NOT_DEFINED" }, + MAC: { H: "HIGH", L: "LOW", X: "NOT_DEFINED" }, + MPR: { N: "NONE", L: "LOW", H: "HIGH", X: "NOT_DEFINED" }, + MUI: { N: "NONE", R: "REQUIRED", X: "NOT_DEFINED" }, + MS: { U: "UNCHANGED", C: "CHANGED", X: "NOT_DEFINED" }, + MCIA: { N: "NONE", L: "LOW", H: "HIGH", X: "NOT_DEFINED" } // C, I and A use the same values +}; + + + +/* ** CVSS31.generateXMLFromMetrics ** + * + * Takes Base, Temporal and Environmental metric values as individual parameters. Their values are in the short format + * defined in the CVSS v3.1 standard definition of the Vector String. For example, the AttackComplexity parameter + * should be either "H" or "L". + * + * Returns a single string containing the metric values in XML form. All Base metrics are required to generate this + * output. All Temporal and Environmental metric values are optional. Any that are not passed will be represented in + * the XML as NOT_DEFINED. The function returns a string for simplicity. It is arguably better to return the XML as + * a DOM object, but at the time of writing this leads to complexity due to older browsers using different JavaScript + * interfaces to do this. Also for simplicity, all Temporal and Environmental metrics are included in the string, + * even though those with a value of "Not Defined" do not need to be included. + * + * The output of this function is an object which always has a property named "success". + * + * If no errors are encountered, success is Boolean "true", and the "xmlString" property contains the XML string + * representation. + * + * If errors are encountered, success is Boolean "false", and other properties are defined as per the + * CVSS31.calculateCVSSFromMetrics function. Refer to the comment for that function for more details. + */ +CVSS31.generateXMLFromMetrics = function ( + AttackVector, AttackComplexity, PrivilegesRequired, UserInteraction, Scope, Confidentiality, Integrity, Availability, + ExploitCodeMaturity, RemediationLevel, ReportConfidence, + ConfidentialityRequirement, IntegrityRequirement, AvailabilityRequirement, + ModifiedAttackVector, ModifiedAttackComplexity, ModifiedPrivilegesRequired, ModifiedUserInteraction, ModifiedScope, + ModifiedConfidentiality, ModifiedIntegrity, ModifiedAvailability) { + + // A string containing the XML we wish to output, with placeholders for the CVSS metrics we will substitute for + // their values, based on the inputs passed to this function. + var xmlTemplate = + '\n' + + '\n' + + '\n' + + ' \n' + + ' __AttackVector__\n' + + ' __AttackComplexity__\n' + + ' __PrivilegesRequired__\n' + + ' __UserInteraction__\n' + + ' __Scope__\n' + + ' __Confidentiality__\n' + + ' __Integrity__\n' + + ' __Availability__\n' + + ' __BaseScore__\n' + + ' __BaseSeverityRating__\n' + + ' \n' + + '\n' + + ' \n' + + ' __ExploitCodeMaturity__\n' + + ' __RemediationLevel__\n' + + ' __ReportConfidence__\n' + + ' __TemporalScore__\n' + + ' __TemporalSeverityRating__\n' + + ' \n' + + '\n' + + ' \n' + + ' __ConfidentialityRequirement__\n' + + ' __IntegrityRequirement__\n' + + ' __AvailabilityRequirement__\n' + + ' __ModifiedAttackVector__\n' + + ' __ModifiedAttackComplexity__\n' + + ' __ModifiedPrivilegesRequired__\n' + + ' __ModifiedUserInteraction__\n' + + ' __ModifiedScope__\n' + + ' __ModifiedConfidentiality__\n' + + ' __ModifiedIntegrity__\n' + + ' __ModifiedAvailability__\n' + + ' __EnvironmentalScore__\n' + + ' __EnvironmentalSeverityRating__\n' + + ' \n' + + '\n' + + '\n'; + + + // Call CVSS31.calculateCVSSFromMetrics to validate all the parameters and generate scores and severity ratings. + // If that function returns an error, immediately return it to the caller of this function. + var result = CVSS31.calculateCVSSFromMetrics ( + AttackVector, AttackComplexity, PrivilegesRequired, UserInteraction, Scope, Confidentiality, Integrity, Availability, + ExploitCodeMaturity, RemediationLevel, ReportConfidence, + ConfidentialityRequirement, IntegrityRequirement, AvailabilityRequirement, + ModifiedAttackVector, ModifiedAttackComplexity, ModifiedPrivilegesRequired, ModifiedUserInteraction, ModifiedScope, + ModifiedConfidentiality, ModifiedIntegrity, ModifiedAvailability); + + if (result.success !== true) { + return result; + } + + var xmlOutput = xmlTemplate; + xmlOutput = xmlOutput.replace ("__AttackVector__", CVSS31.XML_MetricNames["MAV"][AttackVector]); + xmlOutput = xmlOutput.replace ("__AttackComplexity__", CVSS31.XML_MetricNames["MAC"][AttackComplexity]); + xmlOutput = xmlOutput.replace ("__PrivilegesRequired__", CVSS31.XML_MetricNames["MPR"][PrivilegesRequired]); + xmlOutput = xmlOutput.replace ("__UserInteraction__", CVSS31.XML_MetricNames["MUI"][UserInteraction]); + xmlOutput = xmlOutput.replace ("__Scope__", CVSS31.XML_MetricNames["MS"][Scope]); + xmlOutput = xmlOutput.replace ("__Confidentiality__", CVSS31.XML_MetricNames["MCIA"][Confidentiality]); + xmlOutput = xmlOutput.replace ("__Integrity__", CVSS31.XML_MetricNames["MCIA"][Integrity]); + xmlOutput = xmlOutput.replace ("__Availability__", CVSS31.XML_MetricNames["MCIA"][Availability]); + xmlOutput = xmlOutput.replace ("__BaseScore__", result.baseMetricScore); + xmlOutput = xmlOutput.replace ("__BaseSeverityRating__", result.baseSeverity); + + xmlOutput = xmlOutput.replace ("__ExploitCodeMaturity__", CVSS31.XML_MetricNames["E"][ExploitCodeMaturity || "X"]); + xmlOutput = xmlOutput.replace ("__RemediationLevel__", CVSS31.XML_MetricNames["RL"][RemediationLevel || "X"]); + xmlOutput = xmlOutput.replace ("__ReportConfidence__", CVSS31.XML_MetricNames["RC"][ReportConfidence || "X"]); + xmlOutput = xmlOutput.replace ("__TemporalScore__", result.temporalMetricScore); + xmlOutput = xmlOutput.replace ("__TemporalSeverityRating__", result.temporalSeverity); + + xmlOutput = xmlOutput.replace ("__ConfidentialityRequirement__", CVSS31.XML_MetricNames["CIAR"][ConfidentialityRequirement || "X"]); + xmlOutput = xmlOutput.replace ("__IntegrityRequirement__", CVSS31.XML_MetricNames["CIAR"][IntegrityRequirement || "X"]); + xmlOutput = xmlOutput.replace ("__AvailabilityRequirement__", CVSS31.XML_MetricNames["CIAR"][AvailabilityRequirement || "X"]); + xmlOutput = xmlOutput.replace ("__ModifiedAttackVector__", CVSS31.XML_MetricNames["MAV"][ModifiedAttackVector || "X"]); + xmlOutput = xmlOutput.replace ("__ModifiedAttackComplexity__", CVSS31.XML_MetricNames["MAC"][ModifiedAttackComplexity || "X"]); + xmlOutput = xmlOutput.replace ("__ModifiedPrivilegesRequired__", CVSS31.XML_MetricNames["MPR"][ModifiedPrivilegesRequired || "X"]); + xmlOutput = xmlOutput.replace ("__ModifiedUserInteraction__", CVSS31.XML_MetricNames["MUI"][ModifiedUserInteraction || "X"]); + xmlOutput = xmlOutput.replace ("__ModifiedScope__", CVSS31.XML_MetricNames["MS"][ModifiedScope || "X"]); + xmlOutput = xmlOutput.replace ("__ModifiedConfidentiality__", CVSS31.XML_MetricNames["MCIA"][ModifiedConfidentiality || "X"]); + xmlOutput = xmlOutput.replace ("__ModifiedIntegrity__", CVSS31.XML_MetricNames["MCIA"][ModifiedIntegrity || "X"]); + xmlOutput = xmlOutput.replace ("__ModifiedAvailability__", CVSS31.XML_MetricNames["MCIA"][ModifiedAvailability || "X"]); + xmlOutput = xmlOutput.replace ("__EnvironmentalScore__", result.environmentalMetricScore); + xmlOutput = xmlOutput.replace ("__EnvironmentalSeverityRating__", result.environmentalSeverity); + + return { success: true, xmlString: xmlOutput }; +}; + + + +/* ** CVSS31.generateXMLFromVector ** + * + * Takes Base, Temporal and Environmental metric values as a single string in the Vector String format defined + * in the CVSS v3.1 standard definition of the Vector String. + * + * Returns an XML string representation of this input. See the comment for CVSS31.generateXMLFromMetrics for more + * detail on inputs, return values and errors. In addition to the error conditions listed for that function, this + * function can also return: + * "MalformedVectorString", if the Vector String passed is does not conform to the format in the standard; or + * "MultipleDefinitionsOfMetric", if the Vector String is well formed but defines the same metric (or metrics), + * more than once. + */ +CVSS31.generateXMLFromVector = function ( vectorString ) { + + var metricValues = { + AV: undefined, AC: undefined, PR: undefined, UI: undefined, S: undefined, + C: undefined, I: undefined, A: undefined, + E: undefined, RL: undefined, RC: undefined, + CR: undefined, IR: undefined, AR: undefined, + MAV: undefined, MAC: undefined, MPR: undefined, MUI: undefined, MS: undefined, + MC: undefined, MI: undefined, MA: undefined + }; + + // If input validation fails, this array is populated with strings indicating which metrics failed validation. + var badMetrics = []; + + if (!CVSS31.vectorStringRegex_31.test(vectorString)) { + return { success: false, errorType: "MalformedVectorString" }; + } + + var metricNameValue = vectorString.substring(CVSS31.CVSSVersionIdentifier.length).split("/"); + + for (var i in metricNameValue) { + if (metricNameValue.hasOwnProperty(i)) { + + var singleMetric = metricNameValue[i].split(":"); + + if (typeof metricValues[singleMetric[0]] === "undefined") { + metricValues[singleMetric[0]] = singleMetric[1]; + } else { + badMetrics.push(singleMetric[0]); + } + } + } + + if (badMetrics.length > 0) { + return { success: false, errorType: "MultipleDefinitionsOfMetric", errorMetrics: badMetrics }; + } + + return CVSS31.generateXMLFromMetrics ( + metricValues.AV, metricValues.AC, metricValues.PR, metricValues.UI, metricValues.S, + metricValues.C, metricValues.I, metricValues.A, + metricValues.E, metricValues.RL, metricValues.RC, + metricValues.CR, metricValues.IR, metricValues.AR, + metricValues.MAV, metricValues.MAC, metricValues.MPR, metricValues.MUI, metricValues.MS, + metricValues.MC, metricValues.MI, metricValues.MA); +}; diff --git a/templates/base.html b/templates/base.html index 842b196..f9e98e5 100644 --- a/templates/base.html +++ b/templates/base.html @@ -23,6 +23,7 @@ + {% block scripts %} diff --git a/templates/findings/new.html b/templates/findings/new.html index 45095b6..913c235 100644 --- a/templates/findings/new.html +++ b/templates/findings/new.html @@ -9,27 +9,54 @@

New finding

{{ render_form(form) }} -
-
+
+
+
+
Base Score
+
+ +
+
Temporal Score
+
+ +
+
Environmental Score
+
+ +
+
+
+
+
{% endblock %} \ No newline at end of file From 4af1465d61d1df2fe2e83dddc30d1b045231066c Mon Sep 17 00:00:00 2001 From: fillodemanuel <63927071+fillodemanuel@users.noreply.github.com> Date: Wed, 30 Sep 2020 11:39:03 +0200 Subject: [PATCH 6/9] Default value for ASVS-MASVS --- sarna/forms/finding_template.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/sarna/forms/finding_template.py b/sarna/forms/finding_template.py index 0c00785..a8b44c1 100644 --- a/sarna/forms/finding_template.py +++ b/sarna/forms/finding_template.py @@ -11,24 +11,30 @@ class FindingTemplateCreateNewForm( masvs = StringField( label = "MASVS - OWASP Mobile Application Security Verification Standard Requirement #", render_kw = {'placeholder': '0.0.0'}, - validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')] + validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')], + default = "0.0.0" ) asvs = StringField( label = "ASVS - OWASP Application Security Verification Standard Requirement #", render_kw = {'placeholder': '0.0.0'}, - validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')]) + validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')], + default = "0.0.0" + ) class FindingTemplateEditForm(BaseEntityForm(FindingTemplate, hide_attrs={'cvss_v3_score', 'cvss_v3_vector'})): masvs = StringField( label = "MASVS - OWASP Mobile Application Security Verification Standard Requirement #", render_kw = {'placeholder': '0.0.0'}, - validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')] + validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')], + default = "0.0.0" ) asvs = StringField( label = "ASVS - OWASP Application Security Verification Standard Requirement #", render_kw={'placeholder': '0.0.0'}, - validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')]) + validators = [validators.Regexp('[0-9]{1,2}.[0-9]{1,2}.[0-9]{1,2}')], + default = "0.0.0" + ) class FindingTemplateAddTranslationForm(BaseEntityForm( FindingTemplateTranslation, From 41b3bb46234a4d2e2eda88298b406da80c99ef4b Mon Sep 17 00:00:00 2001 From: fillodemanuel <63927071+fillodemanuel@users.noreply.github.com> Date: Wed, 30 Sep 2020 16:22:15 +0200 Subject: [PATCH 7/9] Update hidden inputs for cvss (#18) * Update hidden field values for cvss --- templates/findings/new.html | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/templates/findings/new.html b/templates/findings/new.html index 913c235..cd3b810 100644 --- a/templates/findings/new.html +++ b/templates/findings/new.html @@ -48,15 +48,15 @@

New finding

onchange: function () { var vector = cvss.get()['vector']; var score = parseFloat(cvss.get()['score']); - $('#cvssresults .base-results .vector').val(vector); + $('#cvss_v3_vector').val(vector); if (isNaN(score)) { - $('#cvssresults .base-results .score').val(0); + $('#cvss_v3_score').val(0); } else { - $('#cvssresults .base-results .score').val(score); + $('#cvss_v3_score').val(score); } } }, 2); - cvss.set($('#cvssresults .base-results .vector').val()); + cvss.set($('#cvss_v3_score').val()); }); {% endblock %} \ No newline at end of file From 3f7f9d8abce1a3167a4d790b38fc3faf408f9f9d Mon Sep 17 00:00:00 2001 From: fillodemanuel <63927071+fillodemanuel@users.noreply.github.com> Date: Wed, 30 Sep 2020 16:23:16 +0200 Subject: [PATCH 8/9] Update cvss inputs (#19) * Update hidden fields values for cvss From 7a2d351a639d3f7ef235cf38cdbcc93b96f35c1e Mon Sep 17 00:00:00 2001 From: fillodemanuel <63927071+fillodemanuel@users.noreply.github.com> Date: Thu, 1 Oct 2020 14:13:49 +0200 Subject: [PATCH 9/9] Icons for temp&env metrics (#21) Icons for environmental and temporal metrics. --- static/css/cvss.css | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/static/css/cvss.css b/static/css/cvss.css index 458fedf..77dd8b6 100644 --- a/static/css/cvss.css +++ b/static/css/cvss.css @@ -31,91 +31,91 @@ font-size: 40px; } -.cvssjs i.AVN { +.cvssjs i.AVN, .cvssjs i.MAVN, i.EU { background-position: -3em 0; } -.cvssjs i.AVA { +.cvssjs i.AVA, .cvssjs i.MAVA, i.EF { background-position: -2em 0; } -.cvssjs i.AVL { +.cvssjs i.AVL, .cvssjs i.MAVL, i.EH { background-position: -1em 0; } -.cvssjs i.AVP { +.cvssjs i.AVP, .cvssjs i.MAVP { background-position: 0 0; } -.cvssjs i.ACL { +.cvssjs i.ACL, i.MACL, i.RLT, i.RLW { background-position: -4em 0; } -.cvssjs i.ACH { +.cvssjs i.ACH, i.MACH, i.RLO { background-position: -5em 0; } -.cvssjs i.PRN { +.cvssjs i.PRN, i.EX, i.RLX, i.RCX, i.CRX, i.IRX, i.ARX, i.MAVX, i.MACX, i.MPRX, i.MPRN, i.MUIX, i.MSX, i.MCX, i.MIX, i.MAX { background-position: -6em 0; } -.cvssjs i.PRL { +.cvssjs i.PRL, i.MPRL { background-position: -7em 0; } -.cvssjs i.PRH { +.cvssjs i.PRH, i.MPRH { background-position: -8em 0; } -.cvssjs i.UIN { +.cvssjs i.UIN, i.MUIN { background-position: -10em 0; } -.cvssjs i.UIR { +.cvssjs i.UIR, i.MUIR { background-position: -9em 0; } -.cvssjs i.SC { +.cvssjs i.SC, i.MSCR { background-position: -11em 0; } -.cvssjs i.SU { +.cvssjs i.SU, i.MSU { background-position: -10em 0; } -.cvssjs i.CH { +.cvssjs i.CH, i.MCH, i.CRH, i.RCC { background-position: -14em 0; } -.cvssjs i.CL { +.cvssjs i.CL, i.RCR, i.MCL, i.CRM { background-position: -13em 0; } -.cvssjs i.CN { +.cvssjs i.CN, i.MCN, i.CRL, i.RLU, i.RCU { background-position: -12em 0; } -.cvssjs i.IH { +.cvssjs i.IH, i.MIH, i.IRH { background-position: -16em 0; } -.cvssjs i.IL { +.cvssjs i.IL, i.MIL, i.IRL { background-position: -17em 0; } -.cvssjs i.IN { +.cvssjs i.IN, i.MIN, i.IRN { background-position: -15em 0; } -.cvssjs i.AH { +.cvssjs i.AH, i.MAH, i.ARH { background-position: -20em 0; } -.cvssjs i.AL { +.cvssjs i.AL, i.MAL, i.ARM { background-position: -19em 0; } -.cvssjs i.AN { +.cvssjs i.AN, i.MAN, i.ARL { background-position: -18em 0; }