Coverage Report - org.owasp.dependencycheck.App
 
Classes in this File Line Coverage Branch Coverage Complexity
App
10%
27/255
9%
10/104
7.75
 
 1  
 /*
 2  
  * This file is part of dependency-check-cli.
 3  
  *
 4  
  * Licensed under the Apache License, Version 2.0 (the "License");
 5  
  * you may not use this file except in compliance with the License.
 6  
  * You may obtain a copy of the License at
 7  
  *
 8  
  *     http://www.apache.org/licenses/LICENSE-2.0
 9  
  *
 10  
  * Unless required by applicable law or agreed to in writing, software
 11  
  * distributed under the License is distributed on an "AS IS" BASIS,
 12  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  
  * See the License for the specific language governing permissions and
 14  
  * limitations under the License.
 15  
  *
 16  
  * Copyright (c) 2012 Jeremy Long. All Rights Reserved.
 17  
  */
 18  
 package org.owasp.dependencycheck;
 19  
 
 20  
 import ch.qos.logback.classic.LoggerContext;
 21  
 import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
 22  
 import java.io.File;
 23  
 import java.io.FileNotFoundException;
 24  
 import java.io.IOException;
 25  
 import java.util.ArrayList;
 26  
 import java.util.HashSet;
 27  
 import java.util.List;
 28  
 import java.util.Set;
 29  
 import org.apache.commons.cli.ParseException;
 30  
 import org.owasp.dependencycheck.data.nvdcve.CveDB;
 31  
 import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
 32  
 import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties;
 33  
 import org.owasp.dependencycheck.dependency.Dependency;
 34  
 import org.apache.tools.ant.DirectoryScanner;
 35  
 import org.owasp.dependencycheck.reporting.ReportGenerator;
 36  
 import org.owasp.dependencycheck.utils.Settings;
 37  
 import org.slf4j.Logger;
 38  
 import org.slf4j.LoggerFactory;
 39  
 import ch.qos.logback.core.FileAppender;
 40  
 import org.slf4j.impl.StaticLoggerBinder;
 41  
 
 42  
 /**
 43  
  * The command line interface for the DependencyCheck application.
 44  
  *
 45  
  * @author Jeremy Long
 46  
  */
 47  2
 public class App {
 48  
 
 49  
     /**
 50  
      * The logger.
 51  
      */
 52  1
     private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
 53  
 
 54  
     /**
 55  
      * The main method for the application.
 56  
      *
 57  
      * @param args the command line arguments
 58  
      */
 59  
     public static void main(String[] args) {
 60  
         try {
 61  0
             Settings.initialize();
 62  0
             final App app = new App();
 63  0
             app.run(args);
 64  
         } finally {
 65  0
             Settings.cleanup(true);
 66  0
         }
 67  0
     }
 68  
 
 69  
     /**
 70  
      * Main CLI entry-point into the application.
 71  
      *
 72  
      * @param args the command line arguments
 73  
      */
 74  
     public void run(String[] args) {
 75  0
         final CliParser cli = new CliParser();
 76  
 
 77  
         try {
 78  0
             cli.parse(args);
 79  0
         } catch (FileNotFoundException ex) {
 80  0
             System.err.println(ex.getMessage());
 81  0
             cli.printHelp();
 82  0
             return;
 83  0
         } catch (ParseException ex) {
 84  0
             System.err.println(ex.getMessage());
 85  0
             cli.printHelp();
 86  0
             return;
 87  0
         }
 88  
 
 89  0
         if (cli.getVerboseLog() != null) {
 90  0
             prepareLogger(cli.getVerboseLog());
 91  
         }
 92  
 
 93  0
         if (cli.isPurge()) {
 94  0
             if (cli.getConnectionString() != null) {
 95  0
                 LOGGER.error("Unable to purge the database when using a non-default connection string");
 96  
             } else {
 97  0
                 populateSettings(cli);
 98  
                 File db;
 99  
                 try {
 100  0
                     db = new File(Settings.getDataDirectory(), "dc.h2.db");
 101  0
                     if (db.exists()) {
 102  0
                         if (db.delete()) {
 103  0
                             LOGGER.info("Database file purged; local copy of the NVD has been removed");
 104  
                         } else {
 105  0
                             LOGGER.error("Unable to delete '{}'; please delete the file manually", db.getAbsolutePath());
 106  
                         }
 107  
                     } else {
 108  0
                         LOGGER.error("Unable to purge database; the database file does not exists: {}", db.getAbsolutePath());
 109  
                     }
 110  0
                 } catch (IOException ex) {
 111  0
                     LOGGER.error("Unable to delete the database");
 112  0
                 }
 113  0
             }
 114  0
         } else if (cli.isGetVersion()) {
 115  0
             cli.printVersionInfo();
 116  0
         } else if (cli.isUpdateOnly()) {
 117  0
             populateSettings(cli);
 118  0
             runUpdateOnly();
 119  0
         } else if (cli.isRunScan()) {
 120  0
             populateSettings(cli);
 121  
             try {
 122  0
                 runScan(cli.getReportDirectory(), cli.getReportFormat(), cli.getProjectName(), cli.getScanFiles(),
 123  0
                         cli.getExcludeList(), cli.getSymLinkDepth());
 124  0
             } catch (InvalidScanPathException ex) {
 125  0
                 LOGGER.error("An invalid scan path was detected; unable to scan '//*' paths");
 126  0
             }
 127  
         } else {
 128  0
             cli.printHelp();
 129  
         }
 130  0
     }
 131  
 
 132  
     /**
 133  
      * Scans the specified directories and writes the dependency reports to the reportDirectory.
 134  
      *
 135  
      * @param reportDirectory the path to the directory where the reports will be written
 136  
      * @param outputFormat the output format of the report
 137  
      * @param applicationName the application name for the report
 138  
      * @param files the files/directories to scan
 139  
      * @param excludes the patterns for files/directories to exclude
 140  
      * @param symLinkDepth the depth that symbolic links will be followed
 141  
      *
 142  
      * @throws InvalidScanPathException thrown if the path to scan starts with "//"
 143  
      */
 144  
     private void runScan(String reportDirectory, String outputFormat, String applicationName, String[] files,
 145  
             String[] excludes, int symLinkDepth) throws InvalidScanPathException {
 146  0
         Engine engine = null;
 147  
         try {
 148  0
             engine = new Engine();
 149  0
             final List<String> antStylePaths = new ArrayList<String>();
 150  0
             for (String file : files) {
 151  0
                 final String antPath = ensureCanonicalPath(file);
 152  0
                 antStylePaths.add(antPath);
 153  
             }
 154  
 
 155  0
             final Set<File> paths = new HashSet<File>();
 156  0
             for (String file : antStylePaths) {
 157  0
                 LOGGER.debug("Scanning {}", file);
 158  0
                 final DirectoryScanner scanner = new DirectoryScanner();
 159  0
                 String include = file.replace('\\', '/');
 160  
                 File baseDir;
 161  
 
 162  0
                 if (include.startsWith("//")) {
 163  0
                     throw new InvalidScanPathException("Unable to scan paths specified by //");
 164  
                 } else {
 165  0
                     final int pos = getLastFileSeparator(include);
 166  0
                     final String tmpBase = include.substring(0, pos);
 167  0
                     final String tmpInclude = include.substring(pos + 1);
 168  0
                     if (tmpInclude.indexOf('*') >= 0 || tmpInclude.indexOf('?') >= 0
 169  0
                             || (new File(include)).isFile()) {
 170  0
                         baseDir = new File(tmpBase);
 171  0
                         include = tmpInclude;
 172  
                     } else {
 173  0
                         baseDir = new File(tmpBase, tmpInclude);
 174  0
                         include = "**/*";
 175  
                     }
 176  
                 }
 177  
                 //LOGGER.debug("baseDir: {}", baseDir);
 178  
                 //LOGGER.debug("include: {}", include);
 179  0
                 scanner.setBasedir(baseDir);
 180  0
                 final String[] includes = {include};
 181  0
                 scanner.setIncludes(includes);
 182  0
                 scanner.setMaxLevelsOfSymlinks(symLinkDepth);
 183  0
                 if (symLinkDepth <= 0) {
 184  0
                     scanner.setFollowSymlinks(false);
 185  
                 }
 186  0
                 if (excludes != null && excludes.length > 0) {
 187  0
                     scanner.addExcludes(excludes);
 188  
                 }
 189  0
                 scanner.scan();
 190  0
                 if (scanner.getIncludedFilesCount() > 0) {
 191  0
                     for (String s : scanner.getIncludedFiles()) {
 192  0
                         final File f = new File(baseDir, s);
 193  0
                         LOGGER.debug("Found file {}", f.toString());
 194  0
                         paths.add(f);
 195  
                     }
 196  
                 }
 197  0
             }
 198  0
             engine.scan(paths);
 199  
 
 200  0
             engine.analyzeDependencies();
 201  0
             final List<Dependency> dependencies = engine.getDependencies();
 202  0
             DatabaseProperties prop = null;
 203  0
             CveDB cve = null;
 204  
             try {
 205  0
                 cve = new CveDB();
 206  0
                 cve.open();
 207  0
                 prop = cve.getDatabaseProperties();
 208  0
             } catch (DatabaseException ex) {
 209  0
                 LOGGER.debug("Unable to retrieve DB Properties", ex);
 210  
             } finally {
 211  0
                 if (cve != null) {
 212  0
                     cve.close();
 213  
                 }
 214  
             }
 215  0
             final ReportGenerator report = new ReportGenerator(applicationName, dependencies, engine.getAnalyzers(), prop);
 216  
             try {
 217  0
                 report.generateReports(reportDirectory, outputFormat);
 218  0
             } catch (IOException ex) {
 219  0
                 LOGGER.error("There was an IO error while attempting to generate the report.");
 220  0
                 LOGGER.debug("", ex);
 221  0
             } catch (Throwable ex) {
 222  0
                 LOGGER.error("There was an error while attempting to generate the report.");
 223  0
                 LOGGER.debug("", ex);
 224  0
             }
 225  0
         } catch (DatabaseException ex) {
 226  0
             LOGGER.error("Unable to connect to the dependency-check database; analysis has stopped");
 227  0
             LOGGER.debug("", ex);
 228  
         } finally {
 229  0
             if (engine != null) {
 230  0
                 engine.cleanup();
 231  
             }
 232  
         }
 233  0
     }
 234  
 
 235  
     /**
 236  
      * Only executes the update phase of dependency-check.
 237  
      */
 238  
     private void runUpdateOnly() {
 239  0
         Engine engine = null;
 240  
         try {
 241  0
             engine = new Engine();
 242  0
             engine.doUpdates();
 243  0
         } catch (DatabaseException ex) {
 244  0
             LOGGER.error("Unable to connect to the dependency-check database; analysis has stopped");
 245  0
             LOGGER.debug("", ex);
 246  
         } finally {
 247  0
             if (engine != null) {
 248  0
                 engine.cleanup();
 249  
             }
 250  
         }
 251  0
     }
 252  
 
 253  
     /**
 254  
      * Updates the global Settings.
 255  
      *
 256  
      * @param cli a reference to the CLI Parser that contains the command line arguments used to set the corresponding settings in
 257  
      * the core engine.
 258  
      */
 259  
     private void populateSettings(CliParser cli) {
 260  
 
 261  0
         final boolean autoUpdate = cli.isAutoUpdate();
 262  0
         final String connectionTimeout = cli.getConnectionTimeout();
 263  0
         final String proxyServer = cli.getProxyServer();
 264  0
         final String proxyPort = cli.getProxyPort();
 265  0
         final String proxyUser = cli.getProxyUsername();
 266  0
         final String proxyPass = cli.getProxyPassword();
 267  0
         final String dataDirectory = cli.getDataDirectory();
 268  0
         final File propertiesFile = cli.getPropertiesFile();
 269  0
         final String suppressionFile = cli.getSuppressionFile();
 270  0
         final String nexusUrl = cli.getNexusUrl();
 271  0
         final String databaseDriverName = cli.getDatabaseDriverName();
 272  0
         final String databaseDriverPath = cli.getDatabaseDriverPath();
 273  0
         final String connectionString = cli.getConnectionString();
 274  0
         final String databaseUser = cli.getDatabaseUser();
 275  0
         final String databasePassword = cli.getDatabasePassword();
 276  0
         final String additionalZipExtensions = cli.getAdditionalZipExtensions();
 277  0
         final String pathToMono = cli.getPathToMono();
 278  0
         final String cveMod12 = cli.getModifiedCve12Url();
 279  0
         final String cveMod20 = cli.getModifiedCve20Url();
 280  0
         final String cveBase12 = cli.getBaseCve12Url();
 281  0
         final String cveBase20 = cli.getBaseCve20Url();
 282  0
         final Integer cveValidForHours = cli.getCveValidForHours();
 283  
 
 284  0
         if (propertiesFile != null) {
 285  
             try {
 286  0
                 Settings.mergeProperties(propertiesFile);
 287  0
             } catch (FileNotFoundException ex) {
 288  0
                 LOGGER.error("Unable to load properties file '{}'", propertiesFile.getPath());
 289  0
                 LOGGER.debug("", ex);
 290  0
             } catch (IOException ex) {
 291  0
                 LOGGER.error("Unable to find properties file '{}'", propertiesFile.getPath());
 292  0
                 LOGGER.debug("", ex);
 293  0
             }
 294  
         }
 295  
         // We have to wait until we've merged the properties before attempting to set whether we use
 296  
         // the proxy for Nexus since it could be disabled in the properties, but not explicitly stated
 297  
         // on the command line
 298  0
         final boolean nexusUsesProxy = cli.isNexusUsesProxy();
 299  0
         if (dataDirectory != null) {
 300  0
             Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory);
 301  0
         } else if (System.getProperty("basedir") != null) {
 302  0
             final File dataDir = new File(System.getProperty("basedir"), "data");
 303  0
             Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath());
 304  0
         } else {
 305  0
             final File jarPath = new File(App.class.getProtectionDomain().getCodeSource().getLocation().getPath());
 306  0
             final File base = jarPath.getParentFile();
 307  0
             final String sub = Settings.getString(Settings.KEYS.DATA_DIRECTORY);
 308  0
             final File dataDir = new File(base, sub);
 309  0
             Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath());
 310  
         }
 311  0
         Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate);
 312  0
         Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_SERVER, proxyServer);
 313  0
         Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_PORT, proxyPort);
 314  0
         Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_USERNAME, proxyUser);
 315  0
         Settings.setStringIfNotEmpty(Settings.KEYS.PROXY_PASSWORD, proxyPass);
 316  0
         Settings.setStringIfNotEmpty(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout);
 317  0
         Settings.setStringIfNotEmpty(Settings.KEYS.SUPPRESSION_FILE, suppressionFile);
 318  0
         Settings.setIntIfNotNull(Settings.KEYS.CVE_CHECK_VALID_FOR_HOURS, cveValidForHours);
 319  
 
 320  
         //File Type Analyzer Settings
 321  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_JAR_ENABLED, !cli.isJarDisabled());
 322  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_ARCHIVE_ENABLED, !cli.isArchiveDisabled());
 323  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_PYTHON_DISTRIBUTION_ENABLED, !cli.isPythonDistributionDisabled());
 324  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_PYTHON_PACKAGE_ENABLED, !cli.isPythonPackageDisabled());
 325  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_AUTOCONF_ENABLED, !cli.isAutoconfDisabled());
 326  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_CMAKE_ENABLED, !cli.isCmakeDisabled());
 327  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_NUSPEC_ENABLED, !cli.isNuspecDisabled());
 328  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED, !cli.isAssemblyDisabled());
 329  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_ENABLED, !cli.isBundleAuditDisabled());
 330  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_OPENSSL_ENABLED, !cli.isOpenSSLDisabled());
 331  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_COMPOSER_LOCK_ENABLED, !cli.isComposerDisabled());
 332  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_NODE_PACKAGE_ENABLED, !cli.isNodeJsDisabled());
 333  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_RUBY_GEMSPEC_ENABLED, !cli.isRubyGemspecDisabled());
 334  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, !cli.isCentralDisabled());
 335  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, !cli.isNexusDisabled());
 336  
 
 337  0
         Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, cli.getPathToBundleAudit());
 338  0
         Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl);
 339  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY, nexusUsesProxy);
 340  0
         Settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName);
 341  0
         Settings.setStringIfNotEmpty(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath);
 342  0
         Settings.setStringIfNotEmpty(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
 343  0
         Settings.setStringIfNotEmpty(Settings.KEYS.DB_USER, databaseUser);
 344  0
         Settings.setStringIfNotEmpty(Settings.KEYS.DB_PASSWORD, databasePassword);
 345  0
         Settings.setStringIfNotEmpty(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, additionalZipExtensions);
 346  0
         Settings.setStringIfNotEmpty(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, pathToMono);
 347  0
         if (cveBase12 != null && !cveBase12.isEmpty()) {
 348  0
             Settings.setString(Settings.KEYS.CVE_SCHEMA_1_2, cveBase12);
 349  0
             Settings.setString(Settings.KEYS.CVE_SCHEMA_2_0, cveBase20);
 350  0
             Settings.setString(Settings.KEYS.CVE_MODIFIED_12_URL, cveMod12);
 351  0
             Settings.setString(Settings.KEYS.CVE_MODIFIED_20_URL, cveMod20);
 352  
         }
 353  0
     }
 354  
 
 355  
     /**
 356  
      * Creates a file appender and adds it to logback.
 357  
      *
 358  
      * @param verboseLog the path to the verbose log file
 359  
      */
 360  
     private void prepareLogger(String verboseLog) {
 361  0
         final StaticLoggerBinder loggerBinder = StaticLoggerBinder.getSingleton();
 362  0
         final LoggerContext context = (LoggerContext) loggerBinder.getLoggerFactory();
 363  
 
 364  0
         final PatternLayoutEncoder encoder = new PatternLayoutEncoder();
 365  0
         encoder.setPattern("%d %C:%L%n%-5level - %msg%n");
 366  0
         encoder.setContext(context);
 367  0
         encoder.start();
 368  0
         final FileAppender fa = new FileAppender();
 369  0
         fa.setAppend(true);
 370  0
         fa.setEncoder(encoder);
 371  0
         fa.setContext(context);
 372  0
         fa.setFile(verboseLog);
 373  0
         final File f = new File(verboseLog);
 374  0
         String name = f.getName();
 375  0
         final int i = name.lastIndexOf('.');
 376  0
         if (i > 1) {
 377  0
             name = name.substring(0, i);
 378  
         }
 379  0
         fa.setName(name);
 380  0
         fa.start();
 381  0
         final ch.qos.logback.classic.Logger rootLogger = context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
 382  0
         rootLogger.addAppender(fa);
 383  0
     }
 384  
 
 385  
     /**
 386  
      * Takes a path and resolves it to be a canonical &amp; absolute path. The caveats are that this method will take an Ant style
 387  
      * file selector path (../someDir/**\/*.jar) and convert it to an absolute/canonical path (at least to the left of the first *
 388  
      * or ?).
 389  
      *
 390  
      * @param path the path to canonicalize
 391  
      * @return the canonical path
 392  
      */
 393  
     protected String ensureCanonicalPath(String path) {
 394  2
         String basePath = null;
 395  2
         String wildCards = null;
 396  2
         final String file = path.replace('\\', '/');
 397  2
         if (file.contains("*") || file.contains("?")) {
 398  
 
 399  1
             int pos = getLastFileSeparator(file);
 400  1
             if (pos < 0) {
 401  0
                 return file;
 402  
             }
 403  1
             pos += 1;
 404  1
             basePath = file.substring(0, pos);
 405  1
             wildCards = file.substring(pos);
 406  1
         } else {
 407  1
             basePath = file;
 408  
         }
 409  
 
 410  2
         File f = new File(basePath);
 411  
         try {
 412  2
             f = f.getCanonicalFile();
 413  2
             if (wildCards != null) {
 414  1
                 f = new File(f, wildCards);
 415  
             }
 416  0
         } catch (IOException ex) {
 417  0
             LOGGER.warn("Invalid path '{}' was provided.", path);
 418  0
             LOGGER.debug("Invalid path provided", ex);
 419  2
         }
 420  2
         return f.getAbsolutePath().replace('\\', '/');
 421  
     }
 422  
 
 423  
     /**
 424  
      * Returns the position of the last file separator.
 425  
      *
 426  
      * @param file a file path
 427  
      * @return the position of the last file separator
 428  
      */
 429  
     private int getLastFileSeparator(String file) {
 430  1
         if (file.contains("*") || file.contains("?")) {
 431  1
             int p1 = file.indexOf('*');
 432  1
             int p2 = file.indexOf('?');
 433  1
             p1 = p1 > 0 ? p1 : file.length();
 434  1
             p2 = p2 > 0 ? p2 : file.length();
 435  1
             int pos = p1 < p2 ? p1 : p2;
 436  1
             pos = file.lastIndexOf('/', pos);
 437  1
             return pos;
 438  
         } else {
 439  0
             return file.lastIndexOf('/');
 440  
         }
 441  
     }
 442  
 }