View Javadoc

1   /*
2    * This file is part of dependency-check-maven.
3    *
4    * Dependency-check-maven is free software: you can redistribute it and/or modify it
5    * under the terms of the GNU General Public License as published by the Free
6    * Software Foundation, either version 3 of the License, or (at your option) any
7    * later version.
8    *
9    * Dependency-check-maven is distributed in the hope that it will be useful, but
10   * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11   * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12   * details.
13   *
14   * You should have received a copy of the GNU General Public License along with
15   * dependency-check-maven. If not, see http://www.gnu.org/licenses/.
16   *
17   * Copyright (c) 2013 Jeremy Long. All Rights Reserved.
18   */
19  package org.owasp.dependencycheck.maven;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.io.UnsupportedEncodingException;
25  import java.net.URLEncoder;
26  import java.text.DateFormat;
27  import java.util.Date;
28  import java.util.List;
29  import java.util.Locale;
30  import java.util.logging.Level;
31  import java.util.logging.Logger;
32  import org.apache.maven.doxia.sink.SinkFactory;
33  import org.apache.maven.plugin.AbstractMojo;
34  import org.apache.maven.plugin.MojoExecutionException;
35  import org.apache.maven.project.MavenProject;
36  import java.util.Set;
37  import org.apache.maven.artifact.Artifact;
38  import org.apache.maven.plugins.annotations.Component;
39  import org.apache.maven.plugins.annotations.LifecyclePhase;
40  import org.apache.maven.plugins.annotations.Mojo;
41  import org.apache.maven.plugins.annotations.Parameter;
42  import org.apache.maven.plugins.annotations.ResolutionScope;
43  import org.apache.maven.reporting.MavenMultiPageReport;
44  import org.apache.maven.reporting.MavenReport;
45  import org.apache.maven.reporting.MavenReportException;
46  import org.apache.maven.doxia.sink.Sink;
47  import org.apache.maven.plugin.MojoFailureException;
48  import org.owasp.dependencycheck.Engine;
49  import org.owasp.dependencycheck.dependency.Dependency;
50  import org.owasp.dependencycheck.dependency.Evidence;
51  import org.owasp.dependencycheck.dependency.Identifier;
52  import org.owasp.dependencycheck.dependency.Reference;
53  import org.owasp.dependencycheck.dependency.Vulnerability;
54  import org.owasp.dependencycheck.dependency.VulnerableSoftware;
55  import org.owasp.dependencycheck.reporting.ReportGenerator;
56  import org.owasp.dependencycheck.utils.LogUtils;
57  import org.owasp.dependencycheck.utils.Settings;
58  
59  /**
60   * Maven Plugin that checks project dependencies to see if they have any known
61   * published vulnerabilities.
62   *
63   * @author Jeremy Long (jeremy.long@owasp.org)
64   */
65  @Mojo(name = "check", defaultPhase = LifecyclePhase.COMPILE, threadSafe = true,
66          requiresDependencyResolution = ResolutionScope.RUNTIME_PLUS_SYSTEM,
67          requiresOnline = true)
68  public class DependencyCheckMojo extends AbstractMojo implements MavenMultiPageReport {
69  
70      /**
71       * The properties file location.
72       */
73      private static final String PROPERTIES_FILE = "mojo.properties";
74      /**
75       * Name of the logging properties file.
76       */
77      private static final String LOG_PROPERTIES_FILE = "log.properties";
78      /**
79       * The name of the test scope.
80       */
81      public static final String TEST_SCOPE = "test";
82      // <editor-fold defaultstate="collapsed" desc="Maven bound parameters and components">
83      /**
84       * The Maven Project Object.
85       */
86      @Component
87      private MavenProject project;
88      /**
89       * The name of the site report destination.
90       */
91      @Parameter(property = "report-name", defaultValue = "dependency-check-report")
92      private String reportName;
93      /**
94       * The path to the verbose log
95       */
96      @Parameter(property = "logfile", defaultValue = "")
97      private String logFile;
98      /**
99       * The name of the report to be displayed in the Maven Generated Reports
100      * page
101      */
102     @Parameter(property = "name", defaultValue = "Dependency-Check")
103     private String name;
104     /**
105      * The description of the Dependency-Check report to be displayed in the
106      * Maven Generated Reports page
107      */
108     @Parameter(property = "description", defaultValue = "A report providing details on any published "
109             + "vulnerabilities within project dependencies. This report is a best effort but may contain "
110             + "false positives and false negatives.")
111     private String description;
112     /**
113      * Specifies the destination directory for the generated Dependency-Check
114      * report.
115      */
116     @Parameter(property = "reportOutputDirectory", defaultValue = "${project.reporting.outputDirectory}", required = true)
117     private File reportOutputDirectory;
118     /**
119      * Specifies if the build should be failed if a CVSS score above a specified
120      * level is identified. The default is 11 which means since the CVSS scores
121      * are 0-10, by default the build will never fail.
122      */
123     @Parameter(property = "failBuildOnCVSS", defaultValue = "11", required = true)
124     private float failBuildOnCVSS = 11;
125     /**
126      * The output directory.
127      */
128     @Parameter(defaultValue = "${project.build.directory}", required = true)
129     private File outputDirectory;
130     /**
131      * Sets whether auto-updating of the NVD CVE/CPE data is enabled. It is not
132      * recommended that this be turned to false. Default is true.
133      */
134     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
135     @Parameter(property = "autoupdate", defaultValue = "true", required = true)
136     private boolean autoUpdate = true;
137     /**
138      * The report format to be generated (HTML, XML, VULN, ALL). This
139      * configuration option has no affect if using this within the Site plugin
140      * unless the externalReport is set to true. Default is HTML.
141      */
142     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
143     @Parameter(property = "format", defaultValue = "HTML", required = true)
144     private String format = "HTML";
145     /**
146      * Sets whether or not the external report format should be used.
147      */
148     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
149     @Parameter(property = "externalReport", defaultValue = "false", required = true)
150     private boolean externalReport = false;
151     /**
152      * The Proxy URL.
153      */
154     @SuppressWarnings("CanBeFinal")
155     @Parameter(property = "proxyUrl", defaultValue = "", required = false)
156     private String proxyUrl = null;
157     /**
158      * The Proxy Port.
159      */
160     @SuppressWarnings("CanBeFinal")
161     @Parameter(property = "proxyPort", defaultValue = "", required = false)
162     private String proxyPort = null;
163     /**
164      * The Proxy username.
165      */
166     @SuppressWarnings("CanBeFinal")
167     @Parameter(property = "proxyUsername", defaultValue = "", required = false)
168     private String proxyUsername = null;
169     /**
170      * The Proxy password.
171      */
172     @SuppressWarnings("CanBeFinal")
173     @Parameter(property = "proxyPassword", defaultValue = "", required = false)
174     private String proxyPassword = null;
175     /**
176      * The Connection Timeout.
177      */
178     @SuppressWarnings("CanBeFinal")
179     @Parameter(property = "connectionTimeout", defaultValue = "", required = false)
180     private String connectionTimeout = null;
181 
182     // </editor-fold>
183     /**
184      * Executes the Dependency-Check on the dependent libraries.
185      *
186      * @return the Engine used to scan the dependencies.
187      */
188     private Engine executeDependencyCheck() {
189 
190         final InputStream in = DependencyCheckMojo.class.getClassLoader().getResourceAsStream(LOG_PROPERTIES_FILE);
191         LogUtils.prepareLogger(in, logFile);
192 
193         populateSettings();
194         final Engine engine = new Engine();
195         final Set<Artifact> artifacts = project.getArtifacts();
196         for (Artifact a : artifacts) {
197             if (!TEST_SCOPE.equals(a.getScope())) {
198                 engine.scan(a.getFile().getAbsolutePath());
199             }
200         }
201         engine.analyzeDependencies();
202         return engine;
203     }
204 
205     /**
206      * Generates the reports for a given dependency-check engine.
207      *
208      * @param engine a dependency-check engine
209      */
210     private void generateExternalReports(Engine engine) {
211         final ReportGenerator r = new ReportGenerator(project.getName(), engine.getDependencies(), engine.getAnalyzers());
212         try {
213             r.generateReports(outputDirectory.getCanonicalPath(), format);
214         } catch (IOException ex) {
215             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.SEVERE, null, ex);
216         } catch (Exception ex) {
217             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.SEVERE, null, ex);
218         }
219     }
220 
221     /**
222      * Generates a dependency-check report using the Maven Site format.
223      *
224      * @param engine the engine used to scan the dependencies
225      * @param sink the sink to write the data to
226      */
227     private void generateMavenSiteReport(final Engine engine, Sink sink) {
228         final List<Dependency> dependencies = engine.getDependencies();
229 
230         writeSiteReportHeader(sink, project.getName());
231         writeSiteReportTOC(sink, dependencies);
232 
233         int cnt = 0;
234         for (Dependency d : dependencies) {
235             writeSiteReportDependencyHeader(sink, d);
236             cnt = writeSiteReportDependencyAnalysisExceptions(d, cnt, sink);
237             cnt = writeSiteReportDependencyEvidenceUsed(d, cnt, sink);
238             cnt = writeSiteReportDependencyRelatedDependencies(d, cnt, sink);
239             writeSiteReportDependencyIdentifiers(d, sink);
240             writeSiteReportDependencyVulnerabilities(d, sink, cnt);
241         }
242         sink.body_();
243     }
244 
245     // <editor-fold defaultstate="collapsed" desc="various writeXXXXX methods to generate the Site Report">
246     /**
247      * Writes the vulnerabilities to the site report.
248      *
249      * @param d the dependency
250      * @param sink the sink to write the data to
251      * @param collapsibleHeaderCount the collapsible header count
252      */
253     private void writeSiteReportDependencyVulnerabilities(Dependency d, Sink sink, int collapsibleHeaderCount) {
254         int cnt = collapsibleHeaderCount;
255         if (d.getVulnerabilities() != null && !d.getVulnerabilities().isEmpty()) {
256             for (Vulnerability v : d.getVulnerabilities()) {
257 
258                 sink.paragraph();
259                 sink.bold();
260                 try {
261                     sink.link("http://web.nvd.nist.gov/view/vuln/detail?vulnId=" + URLEncoder.encode(v.getName(), "US-ASCII"));
262                     sink.text(v.getName());
263                     sink.link_();
264                     sink.bold_();
265                 } catch (UnsupportedEncodingException ex) {
266                     sink.text(v.getName());
267                     sink.bold_();
268                     sink.lineBreak();
269                     sink.text("http://web.nvd.nist.gov/view/vuln/detail?vulnId=" + v.getName());
270                 }
271                 sink.paragraph_();
272                 sink.paragraph();
273                 sink.text("Severity: ");
274                 if (v.getCvssScore() < 4.0) {
275                     sink.text("Low");
276                 } else {
277                     if (v.getCvssScore() >= 7.0) {
278                         sink.text("High");
279                     } else {
280                         sink.text("Medium");
281                     }
282                 }
283                 sink.lineBreak();
284                 sink.text("CVSS Score: " + v.getCvssScore());
285                 if (v.getCwe() != null && !v.getCwe().isEmpty()) {
286                     sink.lineBreak();
287                     sink.text("CWE: ");
288                     sink.text(v.getCwe());
289                 }
290                 sink.paragraph_();
291                 sink.paragraph();
292                 sink.text(v.getDescription());
293                 if (v.getReferences() != null && !v.getReferences().isEmpty()) {
294                     sink.list();
295                     for (Reference ref : v.getReferences()) {
296                         sink.listItem();
297                         sink.text(ref.getSource());
298                         sink.text(" - ");
299                         sink.link(ref.getUrl());
300                         sink.text(ref.getName());
301                         sink.link_();
302                         sink.listItem_();
303                     }
304                     sink.list_();
305                 }
306                 sink.paragraph_();
307                 if (v.getVulnerableSoftware() != null && !v.getVulnerableSoftware().isEmpty()) {
308                     sink.paragraph();
309 
310                     cnt += 1;
311                     sink.rawText("Vulnerable Software <a href=\"javascript:toggleElement(this, 'vulnSoft" + cnt + "')\">[-]</a>");
312                     sink.rawText("<div id=\"vulnSoft" + cnt + "\" style=\"display:block\">");
313                     sink.list();
314                     for (VulnerableSoftware vs : v.getVulnerableSoftware()) {
315                         sink.listItem();
316                         try {
317                             sink.link("http://web.nvd.nist.gov/view/vuln/search-results?cpe=" + URLEncoder.encode(vs.getName(), "US-ASCII"));
318                             sink.text(vs.getName());
319                             sink.link_();
320                             if (vs.hasPreviousVersion()) {
321                                 sink.text(" and all previous versions.");
322                             }
323                         } catch (UnsupportedEncodingException ex) {
324                             sink.text(vs.getName());
325                             if (vs.hasPreviousVersion()) {
326                                 sink.text(" and all previous versions.");
327                             }
328                             sink.text(" (http://web.nvd.nist.gov/view/vuln/search-results?cpe=" + vs.getName() + ")");
329                         }
330 
331                         sink.listItem_();
332                     }
333                     sink.list_();
334                     sink.rawText("</div>");
335                     sink.paragraph_();
336                 }
337             }
338         }
339     }
340 
341     /**
342      * Writes the identifiers to the site report.
343      *
344      * @param d the dependency
345      * @param sink the sink to write the data to
346      */
347     private void writeSiteReportDependencyIdentifiers(Dependency d, Sink sink) {
348         if (d.getIdentifiers() != null && !d.getIdentifiers().isEmpty()) {
349             sink.sectionTitle4();
350             sink.text("Identifiers");
351             sink.sectionTitle4_();
352             sink.list();
353             for (Identifier i : d.getIdentifiers()) {
354                 sink.listItem();
355                 sink.text(i.getType());
356                 sink.text(": ");
357                 if (i.getUrl() != null && i.getUrl().length() > 0) {
358                     sink.link(i.getUrl());
359                     sink.text(i.getValue());
360                     sink.link_();
361                 } else {
362                     sink.text(i.getValue());
363                 }
364                 if (i.getDescription() != null && i.getDescription().length() > 0) {
365                     sink.lineBreak();
366                     sink.text(i.getDescription());
367                 }
368                 sink.listItem_();
369             }
370             sink.list_();
371         }
372     }
373 
374     /**
375      * Writes the related dependencies to the site report.
376      *
377      * @param d the dependency
378      * @param sink the sink to write the data to
379      * @param collapsibleHeaderCount the collapsible header count
380      * @return the collapsible header count
381      */
382     private int writeSiteReportDependencyRelatedDependencies(Dependency d, int collapsibleHeaderCount, Sink sink) {
383         int cnt = collapsibleHeaderCount;
384         if (d.getRelatedDependencies() != null && !d.getRelatedDependencies().isEmpty()) {
385             cnt += 1;
386             sink.sectionTitle4();
387             sink.rawText("Related Dependencies <a href=\"javascript:toggleElement(this, 'related" + cnt + "')\">[+]</a>");
388             sink.sectionTitle4_();
389             sink.rawText("<div id=\"related" + cnt + "\" style=\"display:none\">");
390             sink.list();
391             for (Dependency r : d.getRelatedDependencies()) {
392                 sink.listItem();
393                 sink.text(r.getFileName());
394                 sink.list();
395                 writeListItem(sink, "File Path: " + r.getFilePath());
396                 writeListItem(sink, "SHA1: " + r.getSha1sum());
397                 writeListItem(sink, "MD5: " + r.getMd5sum());
398                 sink.list_();
399                 sink.listItem_();
400             }
401             sink.list_();
402             sink.rawText("</div>");
403         }
404         return cnt;
405     }
406 
407     /**
408      * Writes the evidence used to the site report.
409      *
410      * @param d the dependency
411      * @param sink the sink to write the data to
412      * @param collapsibleHeaderCount the collapsible header count
413      * @return the collapsible header count
414      */
415     private int writeSiteReportDependencyEvidenceUsed(Dependency d, int collapsibleHeaderCount, Sink sink) {
416         int cnt = collapsibleHeaderCount;
417         if (d.getEvidenceUsed() != null && d.getEvidenceUsed().size() > 0) {
418             cnt += 1;
419             sink.sectionTitle4();
420             sink.rawText("Evidence Collected <a href=\"javascript:toggleElement(this, 'evidence" + cnt + "')\">[+]</a>");
421             sink.sectionTitle4_();
422             sink.rawText("<div id=\"evidence" + cnt + "\" style=\"display:none\">");
423             sink.table();
424             sink.tableRow();
425             writeTableHeaderCell(sink, "Source");
426             writeTableHeaderCell(sink, "Name");
427             writeTableHeaderCell(sink, "Value");
428             sink.tableRow_();
429             for (Evidence e : d.getEvidenceUsed()) {
430                 sink.tableRow();
431                 writeTableCell(sink, e.getSource());
432                 writeTableCell(sink, e.getName());
433                 writeTableCell(sink, e.getValue());
434                 sink.tableRow_();
435             }
436             sink.table_();
437             sink.rawText("</div>");
438         }
439         return cnt;
440     }
441 
442     /**
443      * Writes the analysis exceptions generated during analysis to the site
444      * report.
445      *
446      * @param d the dependency
447      * @param sink the sink to write the data to
448      * @param collapsibleHeaderCount the collapsible header count
449      * @return the collapsible header count
450      */
451     private int writeSiteReportDependencyAnalysisExceptions(Dependency d, int collapsibleHeaderCount, Sink sink) {
452         int cnt = collapsibleHeaderCount;
453         if (d.getAnalysisExceptions() != null && !d.getAnalysisExceptions().isEmpty()) {
454             cnt += 1;
455             sink.sectionTitle4();
456             sink.rawText("<font style=\"color:red\">Errors occurred during analysis:</font> <a href=\"javascript:toggleElement(this, 'errors"
457                     + cnt + "')\">[+]</a>");
458             sink.sectionTitle4_();
459             sink.rawText("<div id=\"errors" + cnt + "\">");
460             sink.list();
461             for (Exception e : d.getAnalysisExceptions()) {
462                 sink.listItem();
463                 sink.text(e.getMessage());
464                 sink.listItem_();
465             }
466             sink.list_();
467             sink.rawText("</div>");
468         }
469         return cnt;
470     }
471 
472     /**
473      * Writes the dependency header to the site report.
474      *
475      * @param d the dependency
476      * @param sink the sink to write the data to
477      */
478     private void writeSiteReportDependencyHeader(Sink sink, Dependency d) {
479         sink.sectionTitle2();
480         sink.anchor("sha1" + d.getSha1sum());
481         sink.text(d.getFileName());
482         sink.anchor_();
483         sink.sectionTitle2_();
484         if (d.getDescription() != null && d.getDescription().length() > 0) {
485             sink.paragraph();
486             sink.bold();
487             sink.text("Description: ");
488             sink.bold_();
489             sink.text(d.getDescription());
490             sink.paragraph_();
491         }
492         if (d.getLicense() != null && d.getLicense().length() > 0) {
493             sink.paragraph();
494             sink.bold();
495             sink.text("License: ");
496             sink.bold_();
497             if (d.getLicense().startsWith("http://") && !d.getLicense().contains(" ")) {
498                 sink.link(d.getLicense());
499                 sink.text(d.getLicense());
500                 sink.link_();
501             } else {
502                 sink.text(d.getLicense());
503             }
504             sink.paragraph_();
505         }
506     }
507 
508     /**
509      * Adds a list item to the site report.
510      *
511      * @param sink the sink to write the data to
512      * @param text the text to write
513      */
514     private void writeListItem(Sink sink, String text) {
515         sink.listItem();
516         sink.text(text);
517         sink.listItem_();
518     }
519 
520     /**
521      * Adds a table cell to the site report.
522      *
523      * @param sink the sink to write the data to
524      * @param text the text to write
525      */
526     private void writeTableCell(Sink sink, String text) {
527         sink.tableCell();
528         sink.text(text);
529         sink.tableCell_();
530     }
531 
532     /**
533      * Adds a table header cell to the site report.
534      *
535      * @param sink the sink to write the data to
536      * @param text the text to write
537      */
538     private void writeTableHeaderCell(Sink sink, String text) {
539         sink.tableHeaderCell();
540         sink.text(text);
541         sink.tableHeaderCell_();
542     }
543 
544     /**
545      * Writes the TOC for the site report.
546      *
547      * @param sink the sink to write the data to
548      * @param dependencies the dependencies that are being reported on
549      */
550     private void writeSiteReportTOC(Sink sink, final List<Dependency> dependencies) {
551         sink.list();
552         for (Dependency d : dependencies) {
553             sink.listItem();
554             sink.link("#sha1" + d.getSha1sum());
555             sink.text(d.getFileName());
556             sink.link_();
557             if (!d.getVulnerabilities().isEmpty()) {
558                 sink.rawText(" <font style=\"color:red\">•</font>");
559             }
560             if (!d.getRelatedDependencies().isEmpty()) {
561                 sink.list();
562                 for (Dependency r : d.getRelatedDependencies()) {
563                     writeListItem(sink, r.getFileName());
564                 }
565                 sink.list_();
566             }
567             sink.listItem_();
568         }
569         sink.list_();
570     }
571 
572     /**
573      * Writes the site report header.
574      *
575      * @param sink the sink to write the data to
576      * @param projectName the name of the project
577      */
578     private void writeSiteReportHeader(Sink sink, String projectName) {
579         sink.head();
580         sink.title();
581         sink.text("Dependency-Check Report: " + projectName);
582         sink.title_();
583         sink.head_();
584         sink.body();
585         sink.rawText("<script type=\"text/javascript\">");
586         sink.rawText("function toggleElement(el, targetId) {");
587         sink.rawText("if (el.innerText == '[+]') {");
588         sink.rawText("    el.innerText = '[-]';");
589         sink.rawText("    document.getElementById(targetId).style.display='block';");
590         sink.rawText("} else {");
591         sink.rawText("    el.innerText = '[+]';");
592         sink.rawText("    document.getElementById(targetId).style.display='none';");
593         sink.rawText("}");
594 
595         sink.rawText("}");
596         sink.rawText("</script>");
597         sink.section1();
598         sink.sectionTitle1();
599         sink.text("Project: " + projectName);
600         sink.sectionTitle1_();
601         sink.date();
602         final Date now = new Date();
603         sink.text(DateFormat.getDateTimeInstance().format(now));
604         sink.date_();
605         sink.section1_();
606     }
607     // </editor-fold>
608 
609     /**
610      * Takes the properties supplied and updates the dependency-check settings.
611      * Additionally, this sets the system properties required to change the
612      * proxy url, port, and connection timeout.
613      */
614     private void populateSettings() {
615         InputStream mojoProperties = null;
616         try {
617             mojoProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
618             Settings.mergeProperties(mojoProperties);
619         } catch (IOException ex) {
620             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.WARNING, "Unable to load the dependency-check ant task.properties file.");
621             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.FINE, null, ex);
622         } finally {
623             if (mojoProperties != null) {
624                 try {
625                     mojoProperties.close();
626                 } catch (IOException ex) {
627                     Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.FINEST, null, ex);
628                 }
629             }
630         }
631 
632         Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate);
633 
634         if (proxyUrl != null && !proxyUrl.isEmpty()) {
635             Settings.setString(Settings.KEYS.PROXY_URL, proxyUrl);
636         }
637         if (proxyPort != null && !proxyPort.isEmpty()) {
638             Settings.setString(Settings.KEYS.PROXY_PORT, proxyPort);
639         }
640         if (proxyUsername != null && !proxyUsername.isEmpty()) {
641             Settings.setString(Settings.KEYS.PROXY_USERNAME, proxyUsername);
642         }
643         if (proxyPassword != null && !proxyPassword.isEmpty()) {
644             Settings.setString(Settings.KEYS.PROXY_PASSWORD, proxyPassword);
645         }
646         if (connectionTimeout != null && !connectionTimeout.isEmpty()) {
647             Settings.setString(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout);
648         }
649     }
650 
651     /**
652      * Executes the dependency-check and generates the report.
653      *
654      * @throws MojoExecutionException if a maven exception occurs
655      * @throws MojoFailureException thrown if a CVSS score is found that is
656      * higher then the configured level
657      */
658     public void execute() throws MojoExecutionException, MojoFailureException {
659         final Engine engine = executeDependencyCheck();
660         generateExternalReports(engine);
661         if (this.failBuildOnCVSS <= 10) {
662             checkForFailure(engine.getDependencies());
663         }
664     }
665 
666     /**
667      * Generates the Dependency-Check Site Report.
668      *
669      * @param sink the sink to write the report to
670      * @param locale the locale to use when generating the report
671      * @throws MavenReportException if a Maven report exception occurs
672      */
673     public void generate(@SuppressWarnings("deprecation") org.codehaus.doxia.sink.Sink sink,
674             Locale locale) throws MavenReportException {
675         generate((Sink) sink, null, locale);
676     }
677 
678     /**
679      * Generates the Dependency-Check Site Report.
680      *
681      * @param sink the sink to write the report to
682      * @param sinkFactory the sink factory
683      * @param locale the locale to use when generating the report
684      * @throws MavenReportException if a maven report exception occurs
685      */
686     public void generate(Sink sink, SinkFactory sinkFactory, Locale locale) throws MavenReportException {
687         final Engine engine = executeDependencyCheck();
688         generateMavenSiteReport(engine, sink);
689     }
690 
691     // <editor-fold defaultstate="collapsed" desc="required setter/getter methods">
692     /**
693      * Returns the output name.
694      *
695      * @return the output name
696      */
697     public String getOutputName() {
698         return reportName;
699     }
700 
701     /**
702      * Returns the category name.
703      *
704      * @return the category name
705      */
706     public String getCategoryName() {
707         return MavenReport.CATEGORY_PROJECT_REPORTS;
708     }
709 
710     /**
711      * Returns the report name.
712      *
713      * @param locale the location
714      * @return the report name
715      */
716     public String getName(Locale locale) {
717         return name;
718     }
719 
720     /**
721      * Sets the Reporting output directory.
722      *
723      * @param directory the output directory
724      */
725     public void setReportOutputDirectory(File directory) {
726         reportOutputDirectory = directory;
727     }
728 
729     /**
730      * Returns the output directory.
731      *
732      * @return the output directory
733      */
734     public File getReportOutputDirectory() {
735         return reportOutputDirectory;
736     }
737 
738     /**
739      * Gets the description of the Dependency-Check report to be displayed in
740      * the Maven Generated Reports page.
741      *
742      * @param locale The Locale to get the description for
743      * @return the description
744      */
745     public String getDescription(Locale locale) {
746         return description;
747     }
748 
749     /**
750      * Returns whether this is an external report.
751      *
752      * @return true or false;
753      */
754     public boolean isExternalReport() {
755         return externalReport;
756     }
757 
758     /**
759      * Returns whether or not the plugin can generate a report.
760      *
761      * @return true
762      */
763     public boolean canGenerateReport() {
764         return true;
765     }
766     // </editor-fold>
767 
768     /**
769      * Checks to see if a vulnerability has been identified with a CVSS score
770      * that is above the threshold set in the configuration.
771      *
772      * @param dependencies the list of dependency objects
773      * @throws MojoFailureException thrown if a CVSS score is found that is
774      * higher then the threshold set
775      */
776     private void checkForFailure(List<Dependency> dependencies) throws MojoFailureException {
777         final StringBuilder ids = new StringBuilder();
778         for (Dependency d : dependencies) {
779             for (Vulnerability v : d.getVulnerabilities()) {
780                 if (v.getCvssScore() >= failBuildOnCVSS) {
781                     if (ids.length() == 0) {
782                         ids.append(v.getName());
783                     } else {
784                         ids.append(", ").append(v.getName());
785                     }
786                 }
787             }
788         }
789         if (ids.length() > 0) {
790             final String msg = String.format("%n%nDependency-Check Failure:%n"
791                     + "One or more dependencies were identified with vulnerabilities that have a CVSS score greater then '%.1f': %s%n"
792                     + "See the dependency-check report for more details.%n%n", failBuildOnCVSS, ids.toString());
793             throw new MojoFailureException(msg);
794         }
795     }
796 }