View Javadoc
1   /*
2    * This file is part of dependency-check-core.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *
16   * Copyright (c) 2018 Jeremy Long. All Rights Reserved.
17   */
18  package org.owasp.dependencycheck.reporting;
19  
20  import java.util.Collection;
21  import java.util.HashMap;
22  import java.util.List;
23  import java.util.Map;
24  import org.owasp.dependencycheck.dependency.Dependency;
25  import org.owasp.dependencycheck.dependency.Vulnerability;
26  import org.owasp.dependencycheck.dependency.naming.CpeIdentifier;
27  import org.owasp.dependencycheck.dependency.naming.GenericIdentifier;
28  import org.owasp.dependencycheck.dependency.naming.Identifier;
29  import org.owasp.dependencycheck.dependency.naming.PurlIdentifier;
30  import org.owasp.dependencycheck.utils.SeverityUtil;
31  import org.slf4j.Logger;
32  import org.slf4j.LoggerFactory;
33  import us.springett.parsers.cpe.Cpe;
34  import us.springett.parsers.cpe.exceptions.CpeEncodingException;
35  import us.springett.parsers.cpe.util.Convert;
36  
37  /**
38   * Utilities to format items in the Velocity reports.
39   *
40   * @author Jeremy Long
41   */
42  public class ReportTool {
43  
44      /**
45       * The logger.
46       */
47      private static final Logger LOGGER = LoggerFactory.getLogger(ReportTool.class);
48  
49      /**
50       * Converts an identifier into the Suppression string when possible.
51       *
52       * @param id the Identifier to format
53       * @return the formatted suppression string when possible; otherwise
54       * <code>null</code>.
55       */
56      public String identifierToSuppressionId(Identifier id) {
57          if (id instanceof PurlIdentifier) {
58              final PurlIdentifier purl = (PurlIdentifier) id;
59              return purl.toString();
60          } else if (id instanceof CpeIdentifier) {
61              try {
62                  final CpeIdentifier cpeId = (CpeIdentifier) id;
63                  final Cpe cpe = cpeId.getCpe();
64                  return String.format("cpe:/%s:%s:%s", Convert.wellFormedToCpeUri(cpe.getPart()),
65                          Convert.wellFormedToCpeUri(cpe.getWellFormedVendor()),
66                          Convert.wellFormedToCpeUri(cpe.getWellFormedProduct()));
67              } catch (CpeEncodingException ex) {
68                  LOGGER.debug("Unable to convert to cpe URI", ex);
69              }
70          } else if (id instanceof GenericIdentifier) {
71              return id.getValue();
72          }
73          return null;
74      }
75  
76      /**
77       * Estimates the CVSS V2 score for the given severity.
78       *
79       * @param severity the text representation of a score
80       * @return the estimated score
81       */
82      public Double estimateSeverity(String severity) {
83          return SeverityUtil.estimateCvssV2(severity);
84      }
85  
86      /**
87       * Creates a list of SARIF rules for the SARIF report.
88       *
89       * @param dependencies the list of dependencies to extract rules from
90       * @return the list of SARIF rules
91       */
92      public Collection<SarifRule> convertToSarifRules(List<Dependency> dependencies) {
93          final Map<String, SarifRule> rules = new HashMap<>();
94          for (Dependency d : dependencies) {
95              for (Vulnerability v : d.getVulnerabilities()) {
96                  if (!rules.containsKey(v.getName())) {
97                      final SarifRule r = new SarifRule(v.getName(),
98                              buildShortDescription(d, v, v.getKnownExploitedVulnerability() != null),
99                              buildDescription(v.getDescription(), v.getKnownExploitedVulnerability()),
100                             v.getSource().name(),
101                             v.getCvssV2(),
102                             v.getCvssV3());
103                     rules.put(v.getName(), r);
104                 }
105             }
106         }
107         return rules.values();
108     }
109 
110     private String determineScore(Vulnerability vuln) {
111         if (vuln.getUnscoredSeverity() != null) {
112             if ("0.0".equals(vuln.getUnscoredSeverity())) {
113                 return "unknown";
114             } else {
115                 return normalizeSeverity(vuln.getUnscoredSeverity().toLowerCase());
116             }
117         } else if (vuln.getCvssV3() != null && vuln.getCvssV3().getCvssData().getBaseSeverity() != null) {
118             return normalizeSeverity(vuln.getCvssV3().getCvssData().getBaseSeverity().value().toLowerCase());
119         } else if (vuln.getCvssV2() != null && vuln.getCvssV2().getCvssData().getBaseSeverity() != null) {
120             return normalizeSeverity(vuln.getCvssV2().getCvssData().getBaseSeverity());
121         }
122         return "unknown";
123     }
124 
125     public String normalizeSeverity(String sev) {
126         switch (sev.toLowerCase()) {
127             case "critical":
128                 return "critical";
129             case "high":
130                 return "high";
131             case "medium":
132             case "moderate":
133                 return "medium";
134             case "low":
135             case "informational":
136             case "info":
137                 return "low";
138             default:
139                 return "unknown";
140         }
141     }
142 
143     /**
144      * Builds the short description for the Sarif format.
145      *
146      * @param d the dependency
147      * @param vuln the vulnerability
148      * @param knownExploited true if the vulnerability is known to be exploited
149      * @return the short description
150      */
151     private String buildShortDescription(Dependency d, Vulnerability vuln, boolean knownExploited) {
152         final StringBuilder sb = new StringBuilder();
153         sb.append(determineScore(vuln))
154                 .append(" severity - ")
155                 .append(vuln.getName());
156         if (vuln.getCwes() != null && !vuln.getCwes().isEmpty()) {
157             final String cwe = vuln.getCwes().getFullCwes().values().iterator().next();
158             if (cwe != null && !"NVD-CWE-Other".equals(cwe) && !"NVD-CWE-noinfo".equals(cwe)) {
159                 sb.append(" ").append(cwe);
160             }
161         }
162         sb.append(" vulnerability in ");
163         if (d.getSoftwareIdentifiers() != null && !d.getSoftwareIdentifiers().isEmpty()) {
164             sb.append(d.getSoftwareIdentifiers().iterator().next());
165         } else {
166             sb.append(d.getDisplayFileName());
167         }
168         if (knownExploited) {
169             sb.append(" *Known Exploited Vulnerability*");
170         }
171         return sb.toString();
172     }
173 
174     private String buildDescription(String description,
175             org.owasp.dependencycheck.data.knownexploited.json.Vulnerability knownExploitedVulnerability) {
176         final StringBuilder sb = new StringBuilder();
177         if (knownExploitedVulnerability != null) {
178             sb.append("CISA Known Exploited Vulnerability\n");
179             if (knownExploitedVulnerability.getVendorProject() != null) {
180                 sb.append("Vendor/Project: ").append(knownExploitedVulnerability.getVendorProject()).append("\n");
181             }
182             if (knownExploitedVulnerability.getProduct() != null) {
183                 sb.append("Product: ").append(knownExploitedVulnerability.getProduct()).append("\n");
184             }
185             if (knownExploitedVulnerability.getVulnerabilityName() != null) {
186                 sb.append("Vulnerability Name: ").append(knownExploitedVulnerability.getVulnerabilityName()).append("\n");
187             }
188             if (knownExploitedVulnerability.getDateAdded() != null) {
189                 sb.append("Date Added: ").append(knownExploitedVulnerability.getDateAdded()).append("\n");
190             }
191             if (knownExploitedVulnerability.getShortDescription() != null) {
192                 sb.append("Short Description: ").append(knownExploitedVulnerability.getShortDescription()).append("\n");
193             }
194             if (knownExploitedVulnerability.getRequiredAction() != null) {
195                 sb.append("Required Action: ").append(knownExploitedVulnerability.getRequiredAction()).append("\n");
196             }
197             if (knownExploitedVulnerability.getDueDate() != null) {
198                 sb.append("Due Date").append(knownExploitedVulnerability.getDueDate()).append("\n");
199             }
200             if (knownExploitedVulnerability.getNotes() != null) {
201                 sb.append("Notes: ").append(knownExploitedVulnerability.getNotes()).append("\n");
202             }
203             sb.append("\n");
204         }
205         sb.append(description);
206         return sb.toString();
207     }
208 }