View Javadoc
1   /*
2    * This file is part of dependency-check-maven.
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) 2013 Jeremy Long. All Rights Reserved.
17   */
18  package org.owasp.dependencycheck.maven;
19  
20  import java.io.File;
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.io.UnsupportedEncodingException;
24  import java.net.URLEncoder;
25  import java.text.DateFormat;
26  import java.util.Date;
27  import java.util.List;
28  import java.util.Locale;
29  import java.util.Set;
30  import java.util.logging.Level;
31  import java.util.logging.Logger;
32  import org.apache.maven.artifact.Artifact;
33  import org.apache.maven.doxia.sink.Sink;
34  import org.apache.maven.doxia.sink.SinkFactory;
35  import org.apache.maven.plugin.AbstractMojo;
36  import org.apache.maven.plugin.MojoExecutionException;
37  import org.apache.maven.plugin.MojoFailureException;
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.project.MavenProject;
44  import org.apache.maven.reporting.MavenMultiPageReport;
45  import org.apache.maven.reporting.MavenReport;
46  import org.apache.maven.reporting.MavenReportException;
47  import org.apache.maven.settings.Proxy;
48  import org.owasp.dependencycheck.Engine;
49  import org.owasp.dependencycheck.data.nvdcve.CveDB;
50  import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
51  import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties;
52  import org.owasp.dependencycheck.dependency.Dependency;
53  import org.owasp.dependencycheck.dependency.Evidence;
54  import org.owasp.dependencycheck.dependency.Identifier;
55  import org.owasp.dependencycheck.dependency.Reference;
56  import org.owasp.dependencycheck.dependency.Vulnerability;
57  import org.owasp.dependencycheck.dependency.VulnerableSoftware;
58  import org.owasp.dependencycheck.reporting.ReportGenerator;
59  import org.owasp.dependencycheck.utils.LogUtils;
60  import org.owasp.dependencycheck.utils.Settings;
61  
62  /**
63   * Maven Plugin that checks project dependencies to see if they have any known published vulnerabilities.
64   *
65   * @author Jeremy Long <jeremy.long@owasp.org>
66   */
67  @Mojo(name = "check", defaultPhase = LifecyclePhase.COMPILE, threadSafe = true,
68          requiresDependencyResolution = ResolutionScope.RUNTIME_PLUS_SYSTEM,
69          requiresOnline = true)
70  public class DependencyCheckMojo extends AbstractMojo implements MavenMultiPageReport {
71  
72      /**
73       * The properties file location.
74       */
75      private static final String PROPERTIES_FILE = "mojo.properties";
76      /**
77       * Name of the logging properties file.
78       */
79      private static final String LOG_PROPERTIES_FILE = "log.properties";
80      /**
81       * System specific new line character.
82       */
83      private static final String NEW_LINE = System.getProperty("line.separator", "\n").intern();
84      // <editor-fold defaultstate="collapsed" desc="Maven bound parameters and components">
85      /**
86       * The Maven Project Object.
87       */
88      @Component
89      private MavenProject project;
90      /**
91       * The path to the verbose log.
92       */
93      @Parameter(property = "logfile", defaultValue = "")
94      private String logFile;
95      /**
96       * The name of the report to be displayed in the Maven Generated Reports page.
97       */
98      @Parameter(property = "name", defaultValue = "Dependency-Check")
99      private String name;
100     /**
101      * The description of the Dependency-Check report to be displayed in the Maven Generated Reports page.
102      */
103     @Parameter(property = "description", defaultValue = "A report providing details on any published "
104             + "vulnerabilities within project dependencies. This report is a best effort but may contain "
105             + "false positives and false negatives.")
106     private String description;
107     /**
108      * Specifies the destination directory for the generated Dependency-Check report. This generally maps to
109      * "target/site".
110      */
111     @Parameter(property = "reportOutputDirectory", defaultValue = "${project.reporting.outputDirectory}", required = true)
112     private File reportOutputDirectory;
113     /**
114      * The output directory. This generally maps to "target".
115      */
116     @Parameter(defaultValue = "${project.build.directory}", required = true)
117     private File outputDirectory;
118     /**
119      * Specifies if the build should be failed if a CVSS score above a specified level is identified. The default is 11
120      * which means since the CVSS scores are 0-10, by default the build will never fail.
121      */
122     @SuppressWarnings("CanBeFinal")
123     @Parameter(property = "failBuildOnCVSS", defaultValue = "11", required = true)
124     private float failBuildOnCVSS = 11;
125     /**
126      * Sets whether auto-updating of the NVD CVE/CPE data is enabled. It is not recommended that this be turned to
127      * false. Default is true.
128      */
129     @SuppressWarnings("CanBeFinal")
130     @Parameter(property = "autoupdate", defaultValue = "true", required = true)
131     private boolean autoUpdate = true;
132     /**
133      * The report format to be generated (HTML, XML, VULN, ALL). This configuration option has no affect if using this
134      * within the Site plugin unless the externalReport is set to true. Default is HTML.
135      */
136     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
137     @Parameter(property = "format", defaultValue = "HTML", required = true)
138     private String format = "HTML";
139     /**
140      * Sets whether or not the external report format should be used.
141      */
142     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
143     @Parameter(property = "externalReport", defaultValue = "false", required = true)
144     private boolean externalReport = false;
145     /**
146      * The Proxy URL.
147      *
148      * @deprecated Please use mavenSettings instead
149      */
150     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
151     @Parameter(property = "proxyUrl", defaultValue = "", required = false)
152     @Deprecated
153     private String proxyUrl = null;
154 
155     /**
156      * The maven settings.
157      */
158     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
159     @Parameter(property = "mavenSettings", defaultValue = "${settings}", required = false)
160     private org.apache.maven.settings.Settings mavenSettings;
161 
162     /**
163      * The maven settings proxy id.
164      */
165     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
166     @Parameter(property = "mavenSettingsProxyId", required = false)
167     private String mavenSettingsProxyId;
168 
169     /**
170      * The Proxy Port.
171      *
172      * @deprecated Please use mavenSettings instead
173      */
174     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
175     @Parameter(property = "proxyPort", defaultValue = "", required = false)
176     @Deprecated
177     private String proxyPort = null;
178     /**
179      * The Proxy username.
180      *
181      * @deprecated Please use mavenSettings instead
182      */
183     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
184     @Parameter(property = "proxyUsername", defaultValue = "", required = false)
185     @Deprecated
186     private String proxyUsername = null;
187     /**
188      * The Proxy password.
189      *
190      * @deprecated Please use mavenSettings instead
191      */
192     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
193     @Parameter(property = "proxyPassword", defaultValue = "", required = false)
194     @Deprecated
195     private String proxyPassword = null;
196     /**
197      * The Connection Timeout.
198      */
199     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
200     @Parameter(property = "connectionTimeout", defaultValue = "", required = false)
201     private String connectionTimeout = null;
202     /**
203      * The Connection Timeout.
204      */
205     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
206     @Parameter(property = "suppressionFile", defaultValue = "", required = false)
207     private String suppressionFile = null;
208     /**
209      * Flag indicating whether or not to show a summary in the output.
210      */
211     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
212     @Parameter(property = "showSummary", defaultValue = "true", required = false)
213     private boolean showSummary = true;
214 
215     /**
216      * Whether or not the Jar Analyzer is enabled.
217      */
218     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
219     @Parameter(property = "jarAnalyzerEnabled", defaultValue = "true", required = false)
220     private boolean jarAnalyzerEnabled = true;
221 
222     /**
223      * Whether or not the Archive Analyzer is enabled.
224      */
225     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
226     @Parameter(property = "archiveAnalyzerEnabled", defaultValue = "true", required = false)
227     private boolean archiveAnalyzerEnabled = true;
228 
229     /**
230      * Whether or not the .NET Assembly Analyzer is enabled.
231      */
232     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
233     @Parameter(property = "assemblyAnalyzerEnabled", defaultValue = "true", required = false)
234     private boolean assemblyAnalyzerEnabled = true;
235 
236     /**
237      * Whether or not the .NET Nuspec Analyzer is enabled.
238      */
239     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
240     @Parameter(property = "nuspecAnalyzerEnabled", defaultValue = "true", required = false)
241     private boolean nuspecAnalyzerEnabled = true;
242 
243     /**
244      * Whether or not the Nexus Analyzer is enabled.
245      */
246     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
247     @Parameter(property = "nexusAnalyzerEnabled", defaultValue = "true", required = false)
248     private boolean nexusAnalyzerEnabled = true;
249     /**
250      * Whether or not the Nexus Analyzer is enabled.
251      */
252     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
253     @Parameter(property = "nexusUrl", defaultValue = "", required = false)
254     private String nexusUrl;
255     /**
256      * Whether or not the configured proxy is used to connect to Nexus.
257      */
258     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
259     @Parameter(property = "nexusUsesProxy", defaultValue = "true", required = false)
260     private boolean nexusUsesProxy = true;
261     /**
262      * The database connection string.
263      */
264     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
265     @Parameter(property = "connectionString", defaultValue = "", required = false)
266     private String connectionString;
267     /**
268      * The database driver name. An example would be org.h2.Driver.
269      */
270     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
271     @Parameter(property = "databaseDriverName", defaultValue = "", required = false)
272     private String databaseDriverName;
273     /**
274      * The path to the database driver if it is not on the class path.
275      */
276     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
277     @Parameter(property = "databaseDriverPath", defaultValue = "", required = false)
278     private String databaseDriverPath;
279     /**
280      * The database user name.
281      */
282     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
283     @Parameter(property = "databaseUser", defaultValue = "", required = false)
284     private String databaseUser;
285     /**
286      * The password to use when connecting to the database.
287      */
288     @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
289     @Parameter(property = "databasePassword", defaultValue = "", required = false)
290     private String databasePassword;
291     /**
292      * A comma-separated list of file extensions to add to analysis next to jar, zip, ....
293      */
294     @Parameter(property = "zipExtensions", required = false)
295     private String zipExtensions;
296     /**
297      * Skip Analisys for Test Scope Dependencies.
298      */
299     @SuppressWarnings("CanBeFinal")
300     @Parameter(property = "skipTestScope", defaultValue = "true", required = false)
301     private boolean skipTestScope = true;
302     /**
303      * Skip Analisys for Runtime Scope Dependencies.
304      */
305     @SuppressWarnings("CanBeFinal")
306     @Parameter(property = "skipRuntimeScope", defaultValue = "false", required = false)
307     private boolean skipRuntimeScope = false;
308     /**
309      * Skip Analisys for Provided Scope Dependencies.
310      */
311     @SuppressWarnings("CanBeFinal")
312     @Parameter(property = "skipProvidedScope", defaultValue = "false", required = false)
313     private boolean skipProvidedScope = false;
314     /**
315      * The data directory, hold DC SQL DB.
316      */
317     @Parameter(property = "dataDirectory", defaultValue = "", required = false)
318     private String dataDirectory;
319     /**
320      * Data Mirror URL for CVE 1.2.
321      */
322     @Parameter(property = "cveUrl12Modified", defaultValue = "", required = false)
323     private String cveUrl12Modified;
324     /**
325      * Data Mirror URL for CVE 2.0.
326      */
327     @Parameter(property = "cveUrl20Modified", defaultValue = "", required = false)
328     private String cveUrl20Modified;
329     /**
330      * Base Data Mirror URL for CVE 1.2.
331      */
332     @Parameter(property = "cveUrl12Base", defaultValue = "", required = false)
333     private String cveUrl12Base;
334     /**
335      * Data Mirror URL for CVE 2.0.
336      */
337     @Parameter(property = "cveUrl20Base", defaultValue = "", required = false)
338     private String cveUrl20Base;
339 
340     /**
341      * The path to mono for .NET Assembly analysis on non-windows systems.
342      */
343     @Parameter(property = "pathToMono", defaultValue = "", required = false)
344     private String pathToMono;
345 
346     // </editor-fold>
347     /**
348      * Executes the Dependency-Check on the dependent libraries.
349      *
350      * @return the Engine used to scan the dependencies.
351      * @throws DatabaseException thrown if there is an exception connecting to the database
352      */
353     private Engine executeDependencyCheck() throws DatabaseException {
354 
355         final InputStream in = DependencyCheckMojo.class.getClassLoader().getResourceAsStream(LOG_PROPERTIES_FILE);
356         LogUtils.prepareLogger(in, logFile);
357 
358         populateSettings();
359         Engine engine = null;
360         try {
361             engine = new Engine();
362             final Set<Artifact> artifacts = project.getArtifacts();
363             for (Artifact a : artifacts) {
364                 if (skipTestScope && Artifact.SCOPE_TEST.equals(a.getScope())) {
365                     continue;
366                 }
367 
368                 if (skipProvidedScope && Artifact.SCOPE_PROVIDED.equals(a.getScope())) {
369                     continue;
370                 }
371 
372                 if (skipRuntimeScope && !Artifact.SCOPE_RUNTIME.equals(a.getScope())) {
373                     continue;
374                 }
375 
376                 engine.scan(a.getFile().getAbsolutePath());
377             }
378             engine.analyzeDependencies();
379         } finally {
380             if (engine != null) {
381                 engine.cleanup();
382             }
383         }
384         return engine;
385     }
386 
387     /**
388      * Generates the reports for a given dependency-check engine.
389      *
390      * @param engine a dependency-check engine
391      * @param outDirectory the directory to write the reports to
392      */
393     private void generateExternalReports(Engine engine, File outDirectory) {
394         DatabaseProperties prop = null;
395         CveDB cve = null;
396         try {
397             cve = new CveDB();
398             cve.open();
399             prop = cve.getDatabaseProperties();
400         } catch (DatabaseException ex) {
401             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.FINE, "Unable to retrieve DB Properties", ex);
402         } finally {
403             if (cve != null) {
404                 cve.close();
405             }
406         }
407         final ReportGenerator r = new ReportGenerator(project.getName(), engine.getDependencies(), engine.getAnalyzers(), prop);
408         try {
409             r.generateReports(outDirectory.getCanonicalPath(), format);
410         } catch (IOException ex) {
411             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.SEVERE,
412                     "Unexpected exception occurred during analysis; please see the verbose error log for more details.");
413             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.FINE, null, ex);
414         } catch (Throwable ex) {
415             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.SEVERE,
416                     "Unexpected exception occurred during analysis; please see the verbose error log for more details.");
417             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.FINE, null, ex);
418         }
419     }
420 
421     /**
422      * Generates a dependency-check report using the Maven Site format.
423      *
424      * @param engine the engine used to scan the dependencies
425      * @param sink the sink to write the data to
426      */
427     private void generateMavenSiteReport(final Engine engine, Sink sink) {
428         final List<Dependency> dependencies = engine.getDependencies();
429 
430         writeSiteReportHeader(sink, project.getName());
431         writeSiteReportTOC(sink, dependencies);
432 
433         int cnt = 0;
434         for (Dependency d : dependencies) {
435             writeSiteReportDependencyHeader(sink, d);
436             cnt = writeSiteReportDependencyEvidenceUsed(d, cnt, sink);
437             cnt = writeSiteReportDependencyRelatedDependencies(d, cnt, sink);
438             writeSiteReportDependencyIdentifiers(d, sink);
439             writeSiteReportDependencyVulnerabilities(d, sink, cnt);
440         }
441         sink.body_();
442     }
443 
444     // <editor-fold defaultstate="collapsed" desc="various writeXXXXX methods to generate the Site Report">
445     /**
446      * Writes the vulnerabilities to the site report.
447      *
448      * @param d the dependency
449      * @param sink the sink to write the data to
450      * @param collapsibleHeaderCount the collapsible header count
451      */
452     private void writeSiteReportDependencyVulnerabilities(Dependency d, Sink sink, int collapsibleHeaderCount) {
453         int cnt = collapsibleHeaderCount;
454         if (d.getVulnerabilities() != null && !d.getVulnerabilities().isEmpty()) {
455             for (Vulnerability v : d.getVulnerabilities()) {
456 
457                 sink.paragraph();
458                 sink.bold();
459                 try {
460                     sink.link("http://web.nvd.nist.gov/view/vuln/detail?vulnId=" + URLEncoder.encode(v.getName(), "US-ASCII"));
461                     sink.text(v.getName());
462                     sink.link_();
463                     sink.bold_();
464                 } catch (UnsupportedEncodingException ex) {
465                     sink.text(v.getName());
466                     sink.bold_();
467                     sink.lineBreak();
468                     sink.text("http://web.nvd.nist.gov/view/vuln/detail?vulnId=" + v.getName());
469                 }
470                 sink.paragraph_();
471                 sink.paragraph();
472                 sink.text("Severity: ");
473                 if (v.getCvssScore() < 4.0) {
474                     sink.text("Low");
475                 } else {
476                     if (v.getCvssScore() >= 7.0) {
477                         sink.text("High");
478                     } else {
479                         sink.text("Medium");
480                     }
481                 }
482                 sink.lineBreak();
483                 sink.text("CVSS Score: " + v.getCvssScore());
484                 if (v.getCwe() != null && !v.getCwe().isEmpty()) {
485                     sink.lineBreak();
486                     sink.text("CWE: ");
487                     sink.text(v.getCwe());
488                 }
489                 sink.paragraph_();
490                 sink.paragraph();
491                 sink.text(v.getDescription());
492                 if (v.getReferences() != null && !v.getReferences().isEmpty()) {
493                     sink.list();
494                     for (Reference ref : v.getReferences()) {
495                         sink.listItem();
496                         sink.text(ref.getSource());
497                         sink.text(" - ");
498                         sink.link(ref.getUrl());
499                         sink.text(ref.getName());
500                         sink.link_();
501                         sink.listItem_();
502                     }
503                     sink.list_();
504                 }
505                 sink.paragraph_();
506                 if (v.getVulnerableSoftware() != null && !v.getVulnerableSoftware().isEmpty()) {
507                     sink.paragraph();
508 
509                     cnt += 1;
510                     sink.rawText("Vulnerable Software <a href=\"javascript:toggleElement(this, 'vulnSoft" + cnt + "')\">[-]</a>");
511                     sink.rawText("<div id=\"vulnSoft" + cnt + "\" style=\"display:block\">");
512                     sink.list();
513                     for (VulnerableSoftware vs : v.getVulnerableSoftware()) {
514                         sink.listItem();
515                         try {
516                             sink.link("http://web.nvd.nist.gov/view/vuln/search-results?cpe=" + URLEncoder.encode(vs.getName(), "US-ASCII"));
517                             sink.text(vs.getName());
518                             sink.link_();
519                             if (vs.hasPreviousVersion()) {
520                                 sink.text(" and all previous versions.");
521                             }
522                         } catch (UnsupportedEncodingException ex) {
523                             sink.text(vs.getName());
524                             if (vs.hasPreviousVersion()) {
525                                 sink.text(" and all previous versions.");
526                             }
527                             sink.text(" (http://web.nvd.nist.gov/view/vuln/search-results?cpe=" + vs.getName() + ")");
528                         }
529 
530                         sink.listItem_();
531                     }
532                     sink.list_();
533                     sink.rawText("</div>");
534                     sink.paragraph_();
535                 }
536             }
537         }
538     }
539 
540     /**
541      * Writes the identifiers to the site report.
542      *
543      * @param d the dependency
544      * @param sink the sink to write the data to
545      */
546     private void writeSiteReportDependencyIdentifiers(Dependency d, Sink sink) {
547         if (d.getIdentifiers() != null && !d.getIdentifiers().isEmpty()) {
548             sink.sectionTitle4();
549             sink.text("Identifiers");
550             sink.sectionTitle4_();
551             sink.list();
552             for (Identifier i : d.getIdentifiers()) {
553                 sink.listItem();
554                 sink.text(i.getType());
555                 sink.text(": ");
556                 if (i.getUrl() != null && i.getUrl().length() > 0) {
557                     sink.link(i.getUrl());
558                     sink.text(i.getValue());
559                     sink.link_();
560                 } else {
561                     sink.text(i.getValue());
562                 }
563                 if (i.getDescription() != null && i.getDescription().length() > 0) {
564                     sink.lineBreak();
565                     sink.text(i.getDescription());
566                 }
567                 sink.listItem_();
568             }
569             sink.list_();
570         }
571     }
572 
573     /**
574      * Writes the related dependencies to the site report.
575      *
576      * @param d the dependency
577      * @param sink the sink to write the data to
578      * @param collapsibleHeaderCount the collapsible header count
579      * @return the collapsible header count
580      */
581     private int writeSiteReportDependencyRelatedDependencies(Dependency d, int collapsibleHeaderCount, Sink sink) {
582         int cnt = collapsibleHeaderCount;
583         if (d.getRelatedDependencies() != null && !d.getRelatedDependencies().isEmpty()) {
584             cnt += 1;
585             sink.sectionTitle4();
586             sink.rawText("Related Dependencies <a href=\"javascript:toggleElement(this, 'related" + cnt + "')\">[+]</a>");
587             sink.sectionTitle4_();
588             sink.rawText("<div id=\"related" + cnt + "\" style=\"display:none\">");
589             sink.list();
590             for (Dependency r : d.getRelatedDependencies()) {
591                 sink.listItem();
592                 sink.text(r.getFileName());
593                 sink.list();
594                 writeListItem(sink, "File Path: " + r.getFilePath());
595                 writeListItem(sink, "SHA1: " + r.getSha1sum());
596                 writeListItem(sink, "MD5: " + r.getMd5sum());
597                 sink.list_();
598                 sink.listItem_();
599             }
600             sink.list_();
601             sink.rawText("</div>");
602         }
603         return cnt;
604     }
605 
606     /**
607      * Writes the evidence used to the site report.
608      *
609      * @param d the dependency
610      * @param sink the sink to write the data to
611      * @param collapsibleHeaderCount the collapsible header count
612      * @return the collapsible header count
613      */
614     private int writeSiteReportDependencyEvidenceUsed(Dependency d, int collapsibleHeaderCount, Sink sink) {
615         int cnt = collapsibleHeaderCount;
616         if (d.getEvidenceUsed() != null && d.getEvidenceUsed().size() > 0) {
617             cnt += 1;
618             sink.sectionTitle4();
619             sink.rawText("Evidence Collected <a href=\"javascript:toggleElement(this, 'evidence" + cnt + "')\">[+]</a>");
620             sink.sectionTitle4_();
621             sink.rawText("<div id=\"evidence" + cnt + "\" style=\"display:none\">");
622             sink.table();
623             sink.tableRow();
624             writeTableHeaderCell(sink, "Source");
625             writeTableHeaderCell(sink, "Name");
626             writeTableHeaderCell(sink, "Value");
627             sink.tableRow_();
628             for (Evidence e : d.getEvidenceUsed()) {
629                 sink.tableRow();
630                 writeTableCell(sink, e.getSource());
631                 writeTableCell(sink, e.getName());
632                 writeTableCell(sink, e.getValue());
633                 sink.tableRow_();
634             }
635             sink.table_();
636             sink.rawText("</div>");
637         }
638         return cnt;
639     }
640 
641     /**
642      * Writes the dependency header to the site report.
643      *
644      * @param d the dependency
645      * @param sink the sink to write the data to
646      */
647     private void writeSiteReportDependencyHeader(Sink sink, Dependency d) {
648         sink.sectionTitle2();
649         sink.anchor("sha1" + d.getSha1sum());
650         sink.text(d.getFileName());
651         sink.anchor_();
652         sink.sectionTitle2_();
653         if (d.getDescription() != null && d.getDescription().length() > 0) {
654             sink.paragraph();
655             sink.bold();
656             sink.text("Description: ");
657             sink.bold_();
658             sink.text(d.getDescription());
659             sink.paragraph_();
660         }
661         if (d.getLicense() != null && d.getLicense().length() > 0) {
662             sink.paragraph();
663             sink.bold();
664             sink.text("License: ");
665             sink.bold_();
666             if (d.getLicense().startsWith("http://") && !d.getLicense().contains(" ")) {
667                 sink.link(d.getLicense());
668                 sink.text(d.getLicense());
669                 sink.link_();
670             } else {
671                 sink.text(d.getLicense());
672             }
673             sink.paragraph_();
674         }
675     }
676 
677     /**
678      * Adds a list item to the site report.
679      *
680      * @param sink the sink to write the data to
681      * @param text the text to write
682      */
683     private void writeListItem(Sink sink, String text) {
684         sink.listItem();
685         sink.text(text);
686         sink.listItem_();
687     }
688 
689     /**
690      * Adds a table cell to the site report.
691      *
692      * @param sink the sink to write the data to
693      * @param text the text to write
694      */
695     private void writeTableCell(Sink sink, String text) {
696         sink.tableCell();
697         sink.text(text);
698         sink.tableCell_();
699     }
700 
701     /**
702      * Adds a table header cell to the site report.
703      *
704      * @param sink the sink to write the data to
705      * @param text the text to write
706      */
707     private void writeTableHeaderCell(Sink sink, String text) {
708         sink.tableHeaderCell();
709         sink.text(text);
710         sink.tableHeaderCell_();
711     }
712 
713     /**
714      * Writes the TOC for the site report.
715      *
716      * @param sink the sink to write the data to
717      * @param dependencies the dependencies that are being reported on
718      */
719     private void writeSiteReportTOC(Sink sink, final List<Dependency> dependencies) {
720         sink.list();
721         for (Dependency d : dependencies) {
722             sink.listItem();
723             sink.link("#sha1" + d.getSha1sum());
724             sink.text(d.getFileName());
725             sink.link_();
726             if (!d.getVulnerabilities().isEmpty()) {
727                 sink.rawText(" <font style=\"color:red\">•</font>");
728             }
729             if (!d.getRelatedDependencies().isEmpty()) {
730                 sink.list();
731                 for (Dependency r : d.getRelatedDependencies()) {
732                     writeListItem(sink, r.getFileName());
733                 }
734                 sink.list_();
735             }
736             sink.listItem_();
737         }
738         sink.list_();
739     }
740 
741     /**
742      * Writes the site report header.
743      *
744      * @param sink the sink to write the data to
745      * @param projectName the name of the project
746      */
747     private void writeSiteReportHeader(Sink sink, String projectName) {
748         sink.head();
749         sink.title();
750         sink.text("Dependency-Check Report: " + projectName);
751         sink.title_();
752         sink.head_();
753         sink.body();
754         sink.rawText("<script type=\"text/javascript\">");
755         sink.rawText("function toggleElement(el, targetId) {");
756         sink.rawText("if (el.innerText == '[+]') {");
757         sink.rawText("    el.innerText = '[-]';");
758         sink.rawText("    document.getElementById(targetId).style.display='block';");
759         sink.rawText("} else {");
760         sink.rawText("    el.innerText = '[+]';");
761         sink.rawText("    document.getElementById(targetId).style.display='none';");
762         sink.rawText("}");
763 
764         sink.rawText("}");
765         sink.rawText("</script>");
766         sink.section1();
767         sink.sectionTitle1();
768         sink.text("Project: " + projectName);
769         sink.sectionTitle1_();
770         sink.date();
771         final Date now = new Date();
772         sink.text(DateFormat.getDateTimeInstance().format(now));
773         sink.date_();
774         sink.section1_();
775     }
776     // </editor-fold>
777 
778     /**
779      * Returns the maven settings proxy url.
780      *
781      * @param proxy the maven proxy
782      * @return the proxy url
783      */
784     private String getMavenSettingsProxyUrl(Proxy proxy) {
785         return new StringBuilder(proxy.getProtocol()).append("://").append(proxy.getHost()).toString();
786     }
787 
788     /**
789      * Returns the maven proxy.
790      *
791      * @return the maven proxy
792      */
793     private Proxy getMavenProxy() {
794         if (mavenSettings != null) {
795             final List<Proxy> proxies = mavenSettings.getProxies();
796             if (proxies != null && proxies.size() > 0) {
797                 if (mavenSettingsProxyId != null) {
798                     for (Proxy proxy : proxies) {
799                         if (mavenSettingsProxyId.equalsIgnoreCase(proxy.getId())) {
800                             return proxy;
801                         }
802                     }
803                 } else if (proxies.size() == 1) {
804                     return proxies.get(0);
805                 } else {
806                     throw new IllegalStateException("Ambigous proxy definition");
807                 }
808             }
809         }
810         return null;
811     }
812 
813     /**
814      * Takes the properties supplied and updates the dependency-check settings. Additionally, this sets the system
815      * properties required to change the proxy url, port, and connection timeout.
816      */
817     private void populateSettings() {
818         InputStream mojoProperties = null;
819         try {
820             mojoProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
821             Settings.mergeProperties(mojoProperties);
822         } catch (IOException ex) {
823             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.WARNING, "Unable to load the dependency-check ant task.properties file.");
824             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.FINE, null, ex);
825         } finally {
826             if (mojoProperties != null) {
827                 try {
828                     mojoProperties.close();
829                 } catch (IOException ex) {
830                     Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.FINEST, null, ex);
831                 }
832             }
833         }
834 
835         Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate);
836 
837         final Proxy proxy = getMavenProxy();
838         if (proxy != null) {
839             Settings.setString(Settings.KEYS.PROXY_URL, getMavenSettingsProxyUrl(proxy));
840             Settings.setString(Settings.KEYS.PROXY_PORT, Integer.toString(proxy.getPort()));
841             final String userName = proxy.getUsername();
842             final String password = proxy.getPassword();
843             if (userName != null && password != null) {
844                 Settings.setString(Settings.KEYS.PROXY_USERNAME, userName);
845                 Settings.setString(Settings.KEYS.PROXY_PASSWORD, password);
846             }
847         }
848 
849         if (proxyUrl != null && !proxyUrl.isEmpty()) {
850             Settings.setString(Settings.KEYS.PROXY_URL, proxyUrl);
851         }
852         if (proxyPort != null && !proxyPort.isEmpty()) {
853             Settings.setString(Settings.KEYS.PROXY_PORT, proxyPort);
854         }
855         if (proxyUsername != null && !proxyUsername.isEmpty()) {
856             Settings.setString(Settings.KEYS.PROXY_USERNAME, proxyUsername);
857         }
858         if (proxyPassword != null && !proxyPassword.isEmpty()) {
859             Settings.setString(Settings.KEYS.PROXY_PASSWORD, proxyPassword);
860         }
861         if (connectionTimeout != null && !connectionTimeout.isEmpty()) {
862             Settings.setString(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout);
863         }
864         if (suppressionFile != null && !suppressionFile.isEmpty()) {
865             Settings.setString(Settings.KEYS.SUPPRESSION_FILE, suppressionFile);
866         }
867 
868         //File Type Analyzer Settings
869         //JAR ANALYZER
870         Settings.setBoolean(Settings.KEYS.ANALYZER_JAR_ENABLED, jarAnalyzerEnabled);
871         //NUSPEC ANALYZER
872         Settings.setBoolean(Settings.KEYS.ANALYZER_NUSPEC_ENABLED, nuspecAnalyzerEnabled);
873         //NEXUS ANALYZER
874         Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, nexusAnalyzerEnabled);
875         if (nexusUrl != null && !nexusUrl.isEmpty()) {
876             Settings.setString(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl);
877         }
878         Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_PROXY, nexusUsesProxy);
879         //ARCHIVE ANALYZER
880         Settings.setBoolean(Settings.KEYS.ANALYZER_ARCHIVE_ENABLED, archiveAnalyzerEnabled);
881         if (zipExtensions != null && !zipExtensions.isEmpty()) {
882             Settings.setString(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, zipExtensions);
883         }
884         //ASSEMBLY ANALYZER
885         Settings.setBoolean(Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED, assemblyAnalyzerEnabled);
886         if (pathToMono != null && !pathToMono.isEmpty()) {
887             Settings.setString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, pathToMono);
888         }
889 
890         //Database configuration
891         if (databaseDriverName != null && !databaseDriverName.isEmpty()) {
892             Settings.setString(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName);
893         }
894         if (databaseDriverPath != null && !databaseDriverPath.isEmpty()) {
895             Settings.setString(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath);
896         }
897         if (connectionString != null && !connectionString.isEmpty()) {
898             Settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
899         }
900         if (databaseUser != null && !databaseUser.isEmpty()) {
901             Settings.setString(Settings.KEYS.DB_USER, databaseUser);
902         }
903         if (databasePassword != null && !databasePassword.isEmpty()) {
904             Settings.setString(Settings.KEYS.DB_PASSWORD, databasePassword);
905         }
906         // Data Directory
907         if (dataDirectory != null && !dataDirectory.isEmpty()) {
908             Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory);
909         }
910 
911         // Scope Exclusion
912         Settings.setBoolean(Settings.KEYS.SKIP_TEST_SCOPE, skipTestScope);
913         Settings.setBoolean(Settings.KEYS.SKIP_RUNTIME_SCOPE, skipRuntimeScope);
914         Settings.setBoolean(Settings.KEYS.SKIP_PROVIDED_SCOPE, skipProvidedScope);
915 
916         // CVE Data Mirroring
917         if (cveUrl12Modified != null && !cveUrl12Modified.isEmpty()) {
918             Settings.setString(Settings.KEYS.CVE_MODIFIED_12_URL, cveUrl12Modified);
919         }
920         if (cveUrl20Modified != null && !cveUrl20Modified.isEmpty()) {
921             Settings.setString(Settings.KEYS.CVE_MODIFIED_20_URL, cveUrl20Modified);
922         }
923         if (cveUrl12Base != null && !cveUrl12Base.isEmpty()) {
924             Settings.setString(Settings.KEYS.CVE_SCHEMA_1_2, cveUrl12Base);
925         }
926         if (cveUrl20Base != null && !cveUrl20Base.isEmpty()) {
927             Settings.setString(Settings.KEYS.CVE_SCHEMA_2_0, cveUrl20Base);
928         }
929 
930     }
931 
932     /**
933      * Executes the dependency-check and generates the report.
934      *
935      * @throws MojoExecutionException if a maven exception occurs
936      * @throws MojoFailureException thrown if a CVSS score is found that is higher then the configured level
937      */
938     public void execute() throws MojoExecutionException, MojoFailureException {
939         Engine engine = null;
940         try {
941             engine = executeDependencyCheck();
942             generateExternalReports(engine, outputDirectory);
943             if (this.showSummary) {
944                 showSummary(engine.getDependencies());
945             }
946             if (this.failBuildOnCVSS <= 10) {
947                 checkForFailure(engine.getDependencies());
948             }
949         } catch (DatabaseException ex) {
950             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.SEVERE,
951                     "Unable to connect to the dependency-check database; analysis has stopped");
952             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.FINE, "", ex);
953         } finally {
954             if (engine != null) {
955                 engine.cleanup();
956             }
957         }
958     }
959 
960     /**
961      * Generates the Dependency-Check Site Report.
962      *
963      * @param sink the sink to write the report to
964      * @param locale the locale to use when generating the report
965      * @throws MavenReportException if a Maven report exception occurs
966      */
967     public void generate(@SuppressWarnings("deprecation") org.codehaus.doxia.sink.Sink sink,
968             Locale locale) throws MavenReportException {
969         generate((Sink) sink, null, locale);
970     }
971 
972     /**
973      * Generates the Dependency-Check Site Report.
974      *
975      * @param sink the sink to write the report to
976      * @param sinkFactory the sink factory
977      * @param locale the locale to use when generating the report
978      * @throws MavenReportException if a maven report exception occurs
979      */
980     public void generate(Sink sink, SinkFactory sinkFactory, Locale locale) throws MavenReportException {
981         Engine engine = null;
982         try {
983             engine = executeDependencyCheck();
984             if (this.externalReport) {
985                 generateExternalReports(engine, reportOutputDirectory);
986             } else {
987                 generateMavenSiteReport(engine, sink);
988             }
989         } catch (DatabaseException ex) {
990             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.SEVERE,
991                     "Unable to connect to the dependency-check database; analysis has stopped");
992             Logger.getLogger(DependencyCheckMojo.class.getName()).log(Level.FINE, "", ex);
993         } finally {
994             if (engine != null) {
995                 engine.cleanup();
996             }
997         }
998     }
999 
1000     // <editor-fold defaultstate="collapsed" desc="required setter/getter methods">
1001     /**
1002      * Returns the output name.
1003      *
1004      * @return the output name
1005      */
1006     public String getOutputName() {
1007         if ("HTML".equalsIgnoreCase(this.format)
1008                 || "ALL".equalsIgnoreCase(this.format)) {
1009             return "dependency-check-report";
1010         } else if ("XML".equalsIgnoreCase(this.format)) {
1011             return "dependency-check-report.xml#";
1012         } else if ("VULN".equalsIgnoreCase(this.format)) {
1013             return "dependency-check-vulnerability";
1014         } else {
1015             Logger.getLogger(DependencyCheckMojo.class
1016                     .getName()).log(Level.WARNING, "Unknown report format used during site generatation.");
1017             return "dependency-check-report";
1018         }
1019     }
1020 
1021     /**
1022      * Returns the category name.
1023      *
1024      * @return the category name
1025      */
1026     public String getCategoryName() {
1027         return MavenReport.CATEGORY_PROJECT_REPORTS;
1028     }
1029 
1030     /**
1031      * Returns the report name.
1032      *
1033      * @param locale the location
1034      * @return the report name
1035      */
1036     public String getName(Locale locale) {
1037         return name;
1038     }
1039 
1040     /**
1041      * Sets the Reporting output directory.
1042      *
1043      * @param directory the output directory
1044      */
1045     public void setReportOutputDirectory(File directory) {
1046         reportOutputDirectory = directory;
1047     }
1048 
1049     /**
1050      * Returns the output directory.
1051      *
1052      * @return the output directory
1053      */
1054     public File getReportOutputDirectory() {
1055         return reportOutputDirectory;
1056     }
1057 
1058     /**
1059      * Gets the description of the Dependency-Check report to be displayed in the Maven Generated Reports page.
1060      *
1061      * @param locale The Locale to get the description for
1062      * @return the description
1063      */
1064     public String getDescription(Locale locale) {
1065         return description;
1066     }
1067 
1068     /**
1069      * Returns whether this is an external report.
1070      *
1071      * @return true or false;
1072      */
1073     public boolean isExternalReport() {
1074         return externalReport;
1075     }
1076 
1077     /**
1078      * Returns whether or not the plugin can generate a report.
1079      *
1080      * @return true
1081      */
1082     public boolean canGenerateReport() {
1083         return true;
1084     }
1085     // </editor-fold>
1086 
1087     /**
1088      * Checks to see if a vulnerability has been identified with a CVSS score that is above the threshold set in the
1089      * configuration.
1090      *
1091      * @param dependencies the list of dependency objects
1092      * @throws MojoFailureException thrown if a CVSS score is found that is higher then the threshold set
1093      */
1094     private void checkForFailure(List<Dependency> dependencies) throws MojoFailureException {
1095         final StringBuilder ids = new StringBuilder();
1096         for (Dependency d : dependencies) {
1097             boolean addName = true;
1098             for (Vulnerability v : d.getVulnerabilities()) {
1099                 if (v.getCvssScore() >= failBuildOnCVSS) {
1100                     if (addName) {
1101                         addName = false;
1102                         ids.append(NEW_LINE).append(d.getFileName()).append(": ");
1103                         ids.append(v.getName());
1104                     } else {
1105                         ids.append(", ").append(v.getName());
1106                     }
1107                 }
1108             }
1109         }
1110         if (ids.length() > 0) {
1111             final String msg = String.format("%n%nDependency-Check Failure:%n"
1112                     + "One or more dependencies were identified with vulnerabilities that have a CVSS score greater then '%.1f': %s%n"
1113                     + "See the dependency-check report for more details.%n%n", failBuildOnCVSS, ids.toString());
1114             throw new MojoFailureException(msg);
1115         }
1116     }
1117 
1118     /**
1119      * Generates a warning message listing a summary of dependencies and their associated CPE and CVE entries.
1120      *
1121      * @param dependencies a list of dependency objects
1122      */
1123     private void showSummary(List<Dependency> dependencies) {
1124         final StringBuilder summary = new StringBuilder();
1125         for (Dependency d : dependencies) {
1126             boolean firstEntry = true;
1127             final StringBuilder ids = new StringBuilder();
1128             for (Vulnerability v : d.getVulnerabilities()) {
1129                 if (firstEntry) {
1130                     firstEntry = false;
1131                 } else {
1132                     ids.append(", ");
1133                 }
1134                 ids.append(v.getName());
1135             }
1136             if (ids.length() > 0) {
1137                 summary.append(d.getFileName()).append(" (");
1138                 firstEntry = true;
1139                 for (Identifier id : d.getIdentifiers()) {
1140                     if (firstEntry) {
1141                         firstEntry = false;
1142                     } else {
1143                         summary.append(", ");
1144                     }
1145                     summary.append(id.getValue());
1146                 }
1147                 summary.append(") : ").append(ids).append(NEW_LINE);
1148             }
1149         }
1150         if (summary.length() > 0) {
1151             final String msg = String.format("%n%n"
1152                     + "One or more dependencies were identified with known vulnerabilities:%n%n%s"
1153                     + "%n%nSee the dependency-check report for more details.%n%n", summary.toString());
1154             Logger
1155                     .getLogger(DependencyCheckMojo.class
1156                             .getName()).log(Level.WARNING, msg);
1157         }
1158     }
1159 }