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