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) 2012 Jeremy Long. All Rights Reserved.
17   */
18  package org.owasp.dependencycheck.reporting;
19  
20  import com.fasterxml.jackson.core.JsonFactory;
21  import com.fasterxml.jackson.core.JsonGenerator;
22  import com.fasterxml.jackson.core.JsonParser;
23  import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
24  import org.apache.commons.io.FilenameUtils;
25  import org.apache.commons.lang3.StringUtils;
26  import org.apache.commons.text.WordUtils;
27  import org.apache.velocity.VelocityContext;
28  import org.apache.velocity.app.VelocityEngine;
29  import org.apache.velocity.context.Context;
30  import org.owasp.dependencycheck.analyzer.Analyzer;
31  import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties;
32  import org.owasp.dependencycheck.dependency.Dependency;
33  import org.owasp.dependencycheck.dependency.EvidenceType;
34  import org.owasp.dependencycheck.exception.ExceptionCollection;
35  import org.owasp.dependencycheck.exception.ReportException;
36  import org.owasp.dependencycheck.utils.Checksum;
37  import org.owasp.dependencycheck.utils.FileUtils;
38  import org.owasp.dependencycheck.utils.Settings;
39  import org.owasp.dependencycheck.utils.XmlUtils;
40  import org.slf4j.Logger;
41  import org.slf4j.LoggerFactory;
42  import org.xml.sax.InputSource;
43  import org.xml.sax.SAXException;
44  
45  import javax.annotation.concurrent.NotThreadSafe;
46  import javax.xml.XMLConstants;
47  import javax.xml.parsers.ParserConfigurationException;
48  import javax.xml.transform.OutputKeys;
49  import javax.xml.transform.Transformer;
50  import javax.xml.transform.TransformerConfigurationException;
51  import javax.xml.transform.TransformerException;
52  import javax.xml.transform.TransformerFactory;
53  import javax.xml.transform.sax.SAXSource;
54  import javax.xml.transform.sax.SAXTransformerFactory;
55  import javax.xml.transform.stream.StreamResult;
56  import java.io.File;
57  import java.io.FileInputStream;
58  import java.io.FileNotFoundException;
59  import java.io.FileOutputStream;
60  import java.io.IOException;
61  import java.io.InputStream;
62  import java.io.InputStreamReader;
63  import java.io.OutputStream;
64  import java.io.OutputStreamWriter;
65  import java.nio.charset.StandardCharsets;
66  import java.nio.file.Files;
67  import java.time.ZonedDateTime;
68  import java.time.format.DateTimeFormatter;
69  import java.util.List;
70  
71  /**
72   * The ReportGenerator is used to, as the name implies, generate reports.
73   * Internally the generator uses the Velocity Templating Engine. The
74   * ReportGenerator exposes a list of Dependencies to the template when
75   * generating the report.
76   *
77   * @author Jeremy Long
78   */
79  @NotThreadSafe
80  public class ReportGenerator {
81  
82      /**
83       * The logger.
84       */
85      private static final Logger LOGGER = LoggerFactory.getLogger(ReportGenerator.class);
86  
87      /**
88       * An enumeration of the report formats.
89       */
90      public enum Format {
91  
92          /**
93           * Generate all reports.
94           */
95          ALL,
96          /**
97           * Generate XML report.
98           */
99          XML,
100         /**
101          * Generate HTML report.
102          */
103         HTML,
104         /**
105          * Generate JSON report.
106          */
107         JSON,
108         /**
109          * Generate CSV report.
110          */
111         CSV,
112         /**
113          * Generate Sarif report.
114          */
115         SARIF,
116         /**
117          * Generate HTML report without script or non-vulnerable libraries for
118          * Jenkins.
119          */
120         JENKINS,
121         /**
122          * Generate JUNIT report.
123          */
124         JUNIT,
125         /**
126          * Generate Report in GitLab dependency check format.
127          *
128          * @see <a href="https://gitlab.com/gitlab-org/security-products/security-report-schemas/-/blob/master/dist/dependency-scanning-report-format.json">format definition</a>
129          * @see <a href="https://docs.gitlab.com/ee/development/integrations/secure.html">additional explanations on the format</a>
130          */
131         GITLAB
132     }
133 
134     /**
135      * The Velocity Engine.
136      */
137     private final VelocityEngine velocityEngine;
138     /**
139      * The Velocity Engine Context.
140      */
141     private final Context context;
142     /**
143      * The configured settings.
144      */
145     private final Settings settings;
146 
147     //CSOFF: ParameterNumber
148     //CSOFF: LineLength
149 
150     /**
151      * Constructs a new ReportGenerator.
152      *
153      * @param applicationName the application name being analyzed
154      * @param dependencies the list of dependencies
155      * @param analyzers the list of analyzers used
156      * @param properties the database properties (containing timestamps of the
157      * NVD CVE data)
158      * @param settings a reference to the database settings
159      * @param exceptions a collection of exceptions that may have occurred
160      * during the analysis
161      * @since 5.1.0
162      */
163     public ReportGenerator(String applicationName, List<Dependency> dependencies, List<Analyzer> analyzers,
164                            DatabaseProperties properties, Settings settings, ExceptionCollection exceptions) {
165         this(applicationName, null, null, null, dependencies, analyzers, properties, settings, exceptions);
166     }
167 
168     /**
169      * Constructs a new ReportGenerator.
170      *
171      * @param applicationName the application name being analyzed
172      * @param groupID the group id of the project being analyzed
173      * @param artifactID the application id of the project being analyzed
174      * @param version the application version of the project being analyzed
175      * @param dependencies the list of dependencies
176      * @param analyzers the list of analyzers used
177      * @param properties the database properties (containing timestamps of the
178      * NVD CVE data)
179      * @param settings a reference to the database settings
180      * @param exceptions a collection of exceptions that may have occurred
181      * during the analysis
182      * @since 5.1.0
183      */
184     public ReportGenerator(String applicationName, String groupID, String artifactID, String version,
185                            List<Dependency> dependencies, List<Analyzer> analyzers, DatabaseProperties properties,
186                            Settings settings, ExceptionCollection exceptions) {
187         this.settings = settings;
188         velocityEngine = createVelocityEngine();
189         velocityEngine.init();
190         context = createContext(applicationName, dependencies, analyzers, properties, groupID,
191                 artifactID, version, exceptions);
192     }
193 
194     /**
195      * Constructs the velocity context used to generate the dependency-check
196      * reports.
197      *
198      * @param applicationName the application name being analyzed
199      * @param groupID the group id of the project being analyzed
200      * @param artifactID the application id of the project being analyzed
201      * @param version the application version of the project being analyzed
202      * @param dependencies the list of dependencies
203      * @param analyzers the list of analyzers used
204      * @param properties the database properties (containing timestamps of the
205      * NVD CVE data)
206      * @param exceptions a collection of exceptions that may have occurred
207      * during the analysis
208      * @return the velocity context
209      */
210     @SuppressWarnings("JavaTimeDefaultTimeZone")
211     private VelocityContext createContext(String applicationName, List<Dependency> dependencies,
212                                           List<Analyzer> analyzers, DatabaseProperties properties, String groupID,
213                                           String artifactID, String version, ExceptionCollection exceptions) {
214 
215         final ZonedDateTime dt = ZonedDateTime.now();
216         final String scanDate = DateTimeFormatter.RFC_1123_DATE_TIME.format(dt);
217         final String scanDateXML = DateTimeFormatter.ISO_INSTANT.format(dt);
218         final String scanDateJunit = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(dt);
219         final String scanDateGitLab = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(dt.withNano(0));
220 
221         // Remember to update type definitions at templates/velocity_implicit.vm
222         final VelocityContext ctxt = new VelocityContext();
223         ctxt.put("applicationName", applicationName);
224         dependencies.sort(Dependency.NAME_COMPARATOR);
225         ctxt.put("dependencies", dependencies);
226         ctxt.put("analyzers", analyzers);
227         ctxt.put("properties", properties);
228         ctxt.put("scanDate", scanDate);
229         ctxt.put("scanDateXML", scanDateXML);
230         ctxt.put("scanDateJunit", scanDateJunit);
231         ctxt.put("scanDateGitLab", scanDateGitLab);
232         ctxt.put("enc", new EscapeTool());
233         ctxt.put("rpt", new ReportTool());
234         ctxt.put("checksum", Checksum.class);
235         ctxt.put("WordUtils", new WordUtils());
236         ctxt.put("StringUtils", new StringUtils());
237         ctxt.put("VENDOR", EvidenceType.VENDOR);
238         ctxt.put("PRODUCT", EvidenceType.PRODUCT);
239         ctxt.put("VERSION", EvidenceType.VERSION);
240         ctxt.put("version", settings.getString(Settings.KEYS.APPLICATION_VERSION, "Unknown"));
241         ctxt.put("settings", settings);
242         if (version != null) {
243             ctxt.put("applicationVersion", version);
244         }
245         if (artifactID != null) {
246             ctxt.put("artifactID", artifactID);
247         }
248         if (groupID != null) {
249             ctxt.put("groupID", groupID);
250         }
251         if (exceptions != null) {
252             ctxt.put("exceptions", exceptions.getExceptions());
253         }
254         return ctxt;
255     }
256     //CSON: ParameterNumber
257     //CSON: LineLength
258 
259     /**
260      * Creates a new Velocity Engine.
261      *
262      * @return a velocity engine
263      */
264     private VelocityEngine createVelocityEngine() {
265         return new VelocityEngine();
266     }
267 
268     /**
269      * Writes the dependency-check report to the given output location.
270      *
271      * @param outputLocation the path where the reports should be written
272      * @param format the format the report should be written in (a valid member
273      * of {@link Format}) or even the path to a custom velocity template
274      * (either fully qualified or the template name on the class path).
275      * @throws ReportException is thrown if there is an error creating out the
276      * reports
277      */
278     public void write(String outputLocation, String format) throws ReportException {
279         Format reportFormat = null;
280         try {
281             reportFormat = Format.valueOf(format.toUpperCase());
282         } catch (IllegalArgumentException ex) {
283             LOGGER.trace("ignore this exception", ex);
284         }
285 
286         if (reportFormat != null) {
287             write(outputLocation, reportFormat);
288         } else {
289             File out = getReportFile(outputLocation, null);
290             if (out.isDirectory()) {
291                 out = new File(out, FilenameUtils.getBaseName(format));
292                 LOGGER.warn("Writing non-standard VSL output to a directory using template name as file name.");
293             }
294             LOGGER.info("Writing custom report to: {}", out.getAbsolutePath());
295             processTemplate(format, out);
296         }
297 
298     }
299 
300     /**
301      * Writes the dependency-check report(s).
302      *
303      * @param outputLocation the path where the reports should be written
304      * @param format the format the report should be written in (see
305      * {@link Format})
306      * @throws ReportException is thrown if there is an error creating out the
307      * reports
308      */
309     public void write(String outputLocation, Format format) throws ReportException {
310         if (format == Format.ALL) {
311             for (Format f : Format.values()) {
312                 if (f != Format.ALL) {
313                     write(outputLocation, f);
314                 }
315             }
316         } else {
317             final File out = getReportFile(outputLocation, format);
318             final String templateName = format.toString().toLowerCase() + "Report";
319             LOGGER.info("Writing {} report to: {}", format, out.getAbsolutePath());
320             processTemplate(templateName, out);
321             if (settings.getBoolean(Settings.KEYS.PRETTY_PRINT, false)) {
322                 if (format == Format.JSON || format == Format.SARIF) {
323                     pretifyJson(out.getPath());
324                 } else if (format == Format.XML || format == Format.JUNIT) {
325                     pretifyXml(out.getPath());
326                 }
327             }
328         }
329     }
330 
331     /**
332      * Determines the report file name based on the give output location and
333      * format. If the output location contains a full file name that has the
334      * correct extension for the given report type then the output location is
335      * returned. However, if the output location is a directory, this method
336      * will generate the correct name for the given output format.
337      *
338      * @param outputLocation the specified output location
339      * @param format the report format
340      * @return the report File
341      */
342     public static File getReportFile(String outputLocation, Format format) {
343         File outFile = new File(outputLocation);
344         if (outFile.getParentFile() == null) {
345             outFile = new File(".", outputLocation);
346         }
347         final String pathToCheck = outputLocation.toLowerCase();
348         if (format == Format.XML && !pathToCheck.endsWith(".xml")) {
349             return new File(outFile, "dependency-check-report.xml");
350         }
351         if (format == Format.HTML && !pathToCheck.endsWith(".html") && !pathToCheck.endsWith(".htm")) {
352             return new File(outFile, "dependency-check-report.html");
353         }
354         if (format == Format.JENKINS && !pathToCheck.endsWith(".html") && !pathToCheck.endsWith(".htm")) {
355             return new File(outFile, "dependency-check-jenkins.html");
356         }
357         if (format == Format.JSON && !pathToCheck.endsWith(".json")) {
358             return new File(outFile, "dependency-check-report.json");
359         }
360         if (format == Format.CSV && !pathToCheck.endsWith(".csv")) {
361             return new File(outFile, "dependency-check-report.csv");
362         }
363         if (format == Format.JUNIT && !pathToCheck.endsWith(".xml")) {
364             return new File(outFile, "dependency-check-junit.xml");
365         }
366         if (format == Format.SARIF && !pathToCheck.endsWith(".sarif")) {
367             return new File(outFile, "dependency-check-report.sarif");
368         }
369         if (format == Format.GITLAB && !pathToCheck.endsWith(".json")) {
370             return new File(outFile, "dependency-check-gitlab.json");
371         }
372         return outFile;
373     }
374 
375     /**
376      * Generates a report from a given Velocity Template. The template name
377      * provided can be the name of a template contained in the jar file, such as
378      * 'XmlReport' or 'HtmlReport', or the template name can be the path to a
379      * template file.
380      *
381      * @param template the name of the template to load
382      * @param file the output file to write the report to
383      * @throws ReportException is thrown when the report cannot be generated
384      */
385     @SuppressFBWarnings(justification = "try with resources will clean up the output stream", value = {"OBL_UNSATISFIED_OBLIGATION"})
386     protected void processTemplate(String template, File file) throws ReportException {
387         ensureParentDirectoryExists(file);
388         try (OutputStream output = new FileOutputStream(file)) {
389             processTemplate(template, output);
390         } catch (IOException ex) {
391             throw new ReportException(String.format("Unable to write to file: %s", file), ex);
392         }
393     }
394 
395     /**
396      * Generates a report from a given Velocity Template. The template name
397      * provided can be the name of a template contained in the jar file, such as
398      * 'XmlReport' or 'HtmlReport', or the template name can be the path to a
399      * template file.
400      *
401      * @param templateName the name of the template to load
402      * @param outputStream the OutputStream to write the report to
403      * @throws ReportException is thrown when an exception occurs
404      */
405     protected void processTemplate(String templateName, OutputStream outputStream) throws ReportException {
406         try {
407             String logTag;
408             InputStream input;
409             final File f = new File(templateName);
410             if (f.isFile()) {
411                 logTag = templateName;
412                 input = new FileInputStream(f);
413             } else {
414                 logTag = "templates/" + templateName + ".vsl";
415                 input = FileUtils.getResourceAsStream(logTag);
416             }
417 
418             try (InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8);
419                  OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
420                 if (!velocityEngine.evaluate(context, writer, logTag, reader)) {
421                     throw new ReportException("Failed to convert the template into html.");
422                 }
423                 writer.flush();
424             }
425         } catch (FileNotFoundException ex) {
426             throw new ReportException("Unable to locate template file: " + templateName, ex);
427         } catch (IOException ex) {
428             throw new ReportException("Unable to write the report", ex);
429         }
430     }
431 
432     /**
433      * Validates that the given file's parent directory exists. If the directory
434      * does not exist an attempt to create the necessary path is made; if that
435      * fails a ReportException will be raised.
436      *
437      * @param file the file or directory directory
438      * @throws ReportException thrown if the parent directory does not exist and
439      * cannot be created
440      */
441     private void ensureParentDirectoryExists(File file) throws ReportException {
442         if (!file.getParentFile().exists()) {
443             final boolean created = file.getParentFile().mkdirs();
444             if (!created) {
445                 final String msg = String.format("Unable to create directory '%s'.", file.getParentFile().getAbsolutePath());
446                 throw new ReportException(msg);
447             }
448         }
449     }
450 
451     /**
452      * Reformats the given XML file.
453      *
454      * @param path the path to the XML file to be reformatted
455      */
456     private void pretifyXml(String path) {
457         final String outputPath = path + ".pretty";
458         final File in = new File(path);
459         final File out = new File(outputPath);
460         try (OutputStream os = new FileOutputStream(out)) {
461             final TransformerFactory transformerFactory = SAXTransformerFactory.newInstance();
462             transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
463             final Transformer transformer = transformerFactory.newTransformer();
464             transformer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
465             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
466             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
467 
468             final SAXSource saxs = new SAXSource(XmlUtils.buildSecureXmlReader(), new InputSource(path));
469             transformer.transform(saxs, new StreamResult(new OutputStreamWriter(os, StandardCharsets.UTF_8)));
470         } catch (ParserConfigurationException | TransformerConfigurationException ex) {
471             LOGGER.debug("Configuration exception when pretty printing", ex);
472             LOGGER.error("Unable to generate pretty report, caused by: {}", ex.getMessage());
473         } catch (TransformerException | SAXException | IOException ex) {
474             LOGGER.debug("Malformed XML?", ex);
475             LOGGER.error("Unable to generate pretty report, caused by: {}", ex.getMessage());
476         }
477         replaceWithPrettified(out, in);
478     }
479 
480     /**
481      * Reformats the given JSON file.
482      *
483      * @param pathToJson the path to the JSON file to be reformatted
484      * @throws ReportException thrown if the given JSON file is malformed
485      */
486     private void pretifyJson(String pathToJson) throws ReportException {
487         LOGGER.debug("pretify json: {}", pathToJson);
488         final String outputPath = pathToJson + ".pretty";
489         final File in = new File(pathToJson);
490         final File out = new File(outputPath);
491 
492         final JsonFactory factory = new JsonFactory();
493 
494         try (InputStream is = new FileInputStream(in); OutputStream os = new FileOutputStream(out)) {
495 
496             final JsonParser parser = factory.createParser(is);
497             final JsonGenerator generator = factory.createGenerator(os);
498 
499             generator.useDefaultPrettyPrinter();
500 
501             while (parser.nextToken() != null) {
502                 generator.copyCurrentEvent(parser);
503             }
504             generator.flush();
505         } catch (IOException ex) {
506             LOGGER.debug("Malformed JSON?", ex);
507             throw new ReportException("Unable to generate json report", ex);
508         }
509         replaceWithPrettified(out, in);
510     }
511 
512     private void replaceWithPrettified(File prettified, File original) {
513         if (prettified.isFile() && original.isFile() && original.delete()) {
514             try {
515                 Thread.sleep(1000);
516                 Files.move(prettified.toPath(), original.toPath());
517             } catch (IOException ex) {
518                 LOGGER.error("Unable to generate pretty report, caused by: {}", ex.getMessage());
519             } catch (InterruptedException ex) {
520                 Thread.currentThread().interrupt();
521                 LOGGER.error("Unable to generate pretty report, caused by: {}", ex.getMessage());
522             }
523         }
524     }
525 
526 }