Coverage Report - org.owasp.dependencycheck.App
 
Classes in this File Line Coverage Branch Coverage Complexity
App
10%
27/255
6%
10/144
10.625
 
 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.owasp.dependencycheck.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  16
 public class App {
 48  
 
 49  
     /**
 50  
      * The logger.
 51  
      */
 52  8
     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.isGetVersion()) {
 94  0
             cli.printVersionInfo();
 95  0
         } else if (cli.isUpdateOnly()) {
 96  0
             populateSettings(cli);
 97  0
             runUpdateOnly();
 98  0
         } else if (cli.isRunScan()) {
 99  0
             populateSettings(cli);
 100  
             try {
 101  0
                 runScan(cli.getReportDirectory(), cli.getReportFormat(), cli.getApplicationName(), cli.getScanFiles(),
 102  
                         cli.getExcludeList(), cli.getSymLinkDepth());
 103  0
             } catch (InvalidScanPathException ex) {
 104  0
                 LOGGER.error("An invalid scan path was detected; unable to scan '//*' paths");
 105  0
             }
 106  
         } else {
 107  0
             cli.printHelp();
 108  
         }
 109  0
     }
 110  
 
 111  
     /**
 112  
      * Scans the specified directories and writes the dependency reports to the reportDirectory.
 113  
      *
 114  
      * @param reportDirectory the path to the directory where the reports will be written
 115  
      * @param outputFormat the output format of the report
 116  
      * @param applicationName the application name for the report
 117  
      * @param files the files/directories to scan
 118  
      * @param excludes the patterns for files/directories to exclude
 119  
      * @param symLinkDepth the depth that symbolic links will be followed
 120  
      *
 121  
      * @throws InvalidScanPathException thrown if the path to scan starts with "//"
 122  
      */
 123  
     private void runScan(String reportDirectory, String outputFormat, String applicationName, String[] files,
 124  
             String[] excludes, int symLinkDepth) throws InvalidScanPathException {
 125  0
         Engine engine = null;
 126  
         try {
 127  0
             engine = new Engine();
 128  0
             final List<String> antStylePaths = new ArrayList<String>();
 129  0
             for (String file : files) {
 130  0
                 final String antPath = ensureCanonicalPath(file);
 131  0
                 antStylePaths.add(antPath);
 132  
             }
 133  
 
 134  0
             final Set<File> paths = new HashSet<File>();
 135  0
             for (String file : antStylePaths) {
 136  0
                 LOGGER.debug("Scanning {}", file);
 137  0
                 final DirectoryScanner scanner = new DirectoryScanner();
 138  0
                 String include = file.replace('\\', '/');
 139  
                 File baseDir;
 140  
 
 141  0
                 if (include.startsWith("//")) {
 142  0
                     throw new InvalidScanPathException("Unable to scan paths specified by //");
 143  
                 } else {
 144  0
                     final int pos = getLastFileSeparator(include);
 145  0
                     final String tmpBase = include.substring(0, pos);
 146  0
                     final String tmpInclude = include.substring(pos + 1);
 147  0
                     if (tmpInclude.indexOf('*') >= 0 || tmpInclude.indexOf('?') >= 0
 148  
                             || (new File(include)).isFile()) {
 149  0
                         baseDir = new File(tmpBase);
 150  0
                         include = tmpInclude;
 151  
                     } else {
 152  0
                         baseDir = new File(tmpBase, tmpInclude);
 153  0
                         include = "**/*";
 154  
                     }
 155  
                 }
 156  
                 //LOGGER.debug("baseDir: {}", baseDir);
 157  
                 //LOGGER.debug("include: {}", include);
 158  0
                 scanner.setBasedir(baseDir);
 159  0
                 scanner.setIncludes(include);
 160  0
                 scanner.setMaxLevelsOfSymlinks(symLinkDepth);
 161  0
                 if (symLinkDepth <= 0) {
 162  0
                     scanner.setFollowSymlinks(false);
 163  
                 }
 164  0
                 if (excludes != null && excludes.length > 0) {
 165  0
                     scanner.addExcludes(excludes);
 166  
                 }
 167  0
                 scanner.scan();
 168  0
                 if (scanner.getIncludedFilesCount() > 0) {
 169  0
                     for (String s : scanner.getIncludedFiles()) {
 170  0
                         final File f = new File(baseDir, s);
 171  0
                         LOGGER.debug("Found file {}", f.toString());
 172  0
                         paths.add(f);
 173  
                     }
 174  
                 }
 175  0
             }
 176  0
             engine.scan(paths);
 177  
 
 178  0
             engine.analyzeDependencies();
 179  0
             final List<Dependency> dependencies = engine.getDependencies();
 180  0
             DatabaseProperties prop = null;
 181  0
             CveDB cve = null;
 182  
             try {
 183  0
                 cve = new CveDB();
 184  0
                 cve.open();
 185  0
                 prop = cve.getDatabaseProperties();
 186  0
             } catch (DatabaseException ex) {
 187  0
                 LOGGER.debug("Unable to retrieve DB Properties", ex);
 188  
             } finally {
 189  0
                 if (cve != null) {
 190  0
                     cve.close();
 191  
                 }
 192  
             }
 193  0
             final ReportGenerator report = new ReportGenerator(applicationName, dependencies, engine.getAnalyzers(), prop);
 194  
             try {
 195  0
                 report.generateReports(reportDirectory, outputFormat);
 196  0
             } catch (IOException ex) {
 197  0
                 LOGGER.error("There was an IO error while attempting to generate the report.");
 198  0
                 LOGGER.debug("", ex);
 199  0
             } catch (Throwable ex) {
 200  0
                 LOGGER.error("There was an error while attempting to generate the report.");
 201  0
                 LOGGER.debug("", ex);
 202  0
             }
 203  0
         } catch (DatabaseException ex) {
 204  0
             LOGGER.error("Unable to connect to the dependency-check database; analysis has stopped");
 205  0
             LOGGER.debug("", ex);
 206  
         } finally {
 207  0
             if (engine != null) {
 208  0
                 engine.cleanup();
 209  
             }
 210  
         }
 211  0
     }
 212  
 
 213  
     /**
 214  
      * Only executes the update phase of dependency-check.
 215  
      */
 216  
     private void runUpdateOnly() {
 217  0
         Engine engine = null;
 218  
         try {
 219  0
             engine = new Engine();
 220  0
             engine.doUpdates();
 221  0
         } catch (DatabaseException ex) {
 222  0
             LOGGER.error("Unable to connect to the dependency-check database; analysis has stopped");
 223  0
             LOGGER.debug("", ex);
 224  
         } finally {
 225  0
             if (engine != null) {
 226  0
                 engine.cleanup();
 227  
             }
 228  
         }
 229  0
     }
 230  
 
 231  
     /**
 232  
      * Updates the global Settings.
 233  
      *
 234  
      * @param cli a reference to the CLI Parser that contains the command line arguments used to set the corresponding settings in
 235  
      * the core engine.
 236  
      */
 237  
     private void populateSettings(CliParser cli) {
 238  
 
 239  0
         final boolean autoUpdate = cli.isAutoUpdate();
 240  0
         final String connectionTimeout = cli.getConnectionTimeout();
 241  0
         final String proxyServer = cli.getProxyServer();
 242  0
         final String proxyPort = cli.getProxyPort();
 243  0
         final String proxyUser = cli.getProxyUsername();
 244  0
         final String proxyPass = cli.getProxyPassword();
 245  0
         final String dataDirectory = cli.getDataDirectory();
 246  0
         final File propertiesFile = cli.getPropertiesFile();
 247  0
         final String suppressionFile = cli.getSuppressionFile();
 248  0
         final boolean jarDisabled = cli.isJarDisabled();
 249  0
         final boolean archiveDisabled = cli.isArchiveDisabled();
 250  0
         final boolean pyDistDisabled = cli.isPythonDistributionDisabled();
 251  0
         final boolean cMakeDisabled = cli.isCmakeDisabled();
 252  0
         final boolean pyPkgDisabled = cli.isPythonPackageDisabled();
 253  0
         final boolean autoconfDisabled = cli.isAutoconfDisabled();
 254  0
         final boolean assemblyDisabled = cli.isAssemblyDisabled();
 255  0
         final boolean nuspecDisabled = cli.isNuspecDisabled();
 256  0
         final boolean centralDisabled = cli.isCentralDisabled();
 257  0
         final boolean nexusDisabled = cli.isNexusDisabled();
 258  0
         final String nexusUrl = cli.getNexusUrl();
 259  0
         final String databaseDriverName = cli.getDatabaseDriverName();
 260  0
         final String databaseDriverPath = cli.getDatabaseDriverPath();
 261  0
         final String connectionString = cli.getConnectionString();
 262  0
         final String databaseUser = cli.getDatabaseUser();
 263  0
         final String databasePassword = cli.getDatabasePassword();
 264  0
         final String additionalZipExtensions = cli.getAdditionalZipExtensions();
 265  0
         final String pathToMono = cli.getPathToMono();
 266  0
         final String cveMod12 = cli.getModifiedCve12Url();
 267  0
         final String cveMod20 = cli.getModifiedCve20Url();
 268  0
         final String cveBase12 = cli.getBaseCve12Url();
 269  0
         final String cveBase20 = cli.getBaseCve20Url();
 270  
 
 271  0
         if (propertiesFile != null) {
 272  
             try {
 273  0
                 Settings.mergeProperties(propertiesFile);
 274  0
             } catch (FileNotFoundException ex) {
 275  0
                 LOGGER.error("Unable to load properties file '{}'", propertiesFile.getPath());
 276  0
                 LOGGER.debug("", ex);
 277  0
             } catch (IOException ex) {
 278  0
                 LOGGER.error("Unable to find properties file '{}'", propertiesFile.getPath());
 279  0
                 LOGGER.debug("", ex);
 280  0
             }
 281  
         }
 282  
         // We have to wait until we've merged the properties before attempting to set whether we use
 283  
         // the proxy for Nexus since it could be disabled in the properties, but not explicitly stated
 284  
         // on the command line
 285  0
         final boolean nexusUsesProxy = cli.isNexusUsesProxy();
 286  0
         if (dataDirectory != null) {
 287  0
             Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory);
 288  0
         } else if (System.getProperty("basedir") != null) {
 289  0
             final File dataDir = new File(System.getProperty("basedir"), "data");
 290  0
             Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath());
 291  0
         } else {
 292  0
             final File jarPath = new File(App.class.getProtectionDomain().getCodeSource().getLocation().getPath());
 293  0
             final File base = jarPath.getParentFile();
 294  0
             final String sub = Settings.getString(Settings.KEYS.DATA_DIRECTORY);
 295  0
             final File dataDir = new File(base, sub);
 296  0
             Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath());
 297  
         }
 298  0
         Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate);
 299  0
         if (proxyServer != null && !proxyServer.isEmpty()) {
 300  0
             Settings.setString(Settings.KEYS.PROXY_SERVER, proxyServer);
 301  
         }
 302  0
         if (proxyPort != null && !proxyPort.isEmpty()) {
 303  0
             Settings.setString(Settings.KEYS.PROXY_PORT, proxyPort);
 304  
         }
 305  0
         if (proxyUser != null && !proxyUser.isEmpty()) {
 306  0
             Settings.setString(Settings.KEYS.PROXY_USERNAME, proxyUser);
 307  
         }
 308  0
         if (proxyPass != null && !proxyPass.isEmpty()) {
 309  0
             Settings.setString(Settings.KEYS.PROXY_PASSWORD, proxyPass);
 310  
         }
 311  0
         if (connectionTimeout != null && !connectionTimeout.isEmpty()) {
 312  0
             Settings.setString(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout);
 313  
         }
 314  0
         if (suppressionFile != null && !suppressionFile.isEmpty()) {
 315  0
             Settings.setString(Settings.KEYS.SUPPRESSION_FILE, suppressionFile);
 316  
         }
 317  
 
 318  
         //File Type Analyzer Settings
 319  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_JAR_ENABLED, !jarDisabled);
 320  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_ARCHIVE_ENABLED, !archiveDisabled);
 321  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_PYTHON_DISTRIBUTION_ENABLED, !pyDistDisabled);
 322  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_PYTHON_PACKAGE_ENABLED, !pyPkgDisabled);
 323  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_AUTOCONF_ENABLED, !autoconfDisabled);
 324  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_CMAKE_ENABLED, !cMakeDisabled);
 325  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_NUSPEC_ENABLED, !nuspecDisabled);
 326  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_ASSEMBLY_ENABLED, !assemblyDisabled);
 327  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_OPENSSL_ENABLED, !cli.isOpenSSLDisabled());
 328  
 
 329  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, !centralDisabled);
 330  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, !nexusDisabled);
 331  0
         if (nexusUrl != null && !nexusUrl.isEmpty()) {
 332  0
             Settings.setString(Settings.KEYS.ANALYZER_NEXUS_URL, nexusUrl);
 333  
         }
 334  0
         Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_PROXY, nexusUsesProxy);
 335  0
         if (databaseDriverName != null && !databaseDriverName.isEmpty()) {
 336  0
             Settings.setString(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName);
 337  
         }
 338  0
         if (databaseDriverPath != null && !databaseDriverPath.isEmpty()) {
 339  0
             Settings.setString(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath);
 340  
         }
 341  0
         if (connectionString != null && !connectionString.isEmpty()) {
 342  0
             Settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
 343  
         }
 344  0
         if (databaseUser != null && !databaseUser.isEmpty()) {
 345  0
             Settings.setString(Settings.KEYS.DB_USER, databaseUser);
 346  
         }
 347  0
         if (databasePassword != null && !databasePassword.isEmpty()) {
 348  0
             Settings.setString(Settings.KEYS.DB_PASSWORD, databasePassword);
 349  
         }
 350  0
         if (additionalZipExtensions != null && !additionalZipExtensions.isEmpty()) {
 351  0
             Settings.setString(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, additionalZipExtensions);
 352  
         }
 353  0
         if (pathToMono != null && !pathToMono.isEmpty()) {
 354  0
             Settings.setString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, pathToMono);
 355  
         }
 356  0
         if (cveBase12 != null && !cveBase12.isEmpty()) {
 357  0
             Settings.setString(Settings.KEYS.CVE_SCHEMA_1_2, cveBase12);
 358  0
             Settings.setString(Settings.KEYS.CVE_SCHEMA_2_0, cveBase20);
 359  0
             Settings.setString(Settings.KEYS.CVE_MODIFIED_12_URL, cveMod12);
 360  0
             Settings.setString(Settings.KEYS.CVE_MODIFIED_20_URL, cveMod20);
 361  
         }
 362  0
     }
 363  
 
 364  
     /**
 365  
      * Creates a file appender and adds it to logback.
 366  
      *
 367  
      * @param verboseLog the path to the verbose log file
 368  
      */
 369  
     private void prepareLogger(String verboseLog) {
 370  0
         final StaticLoggerBinder loggerBinder = StaticLoggerBinder.getSingleton();
 371  0
         final LoggerContext context = (LoggerContext) loggerBinder.getLoggerFactory();
 372  
 
 373  0
         final PatternLayoutEncoder encoder = new PatternLayoutEncoder();
 374  0
         encoder.setPattern("%d %C:%L%n%-5level - %msg%n");
 375  0
         encoder.setContext(context);
 376  0
         encoder.start();
 377  0
         final FileAppender fa = new FileAppender();
 378  0
         fa.setAppend(true);
 379  0
         fa.setEncoder(encoder);
 380  0
         fa.setContext(context);
 381  0
         fa.setFile(verboseLog);
 382  0
         final File f = new File(verboseLog);
 383  0
         String name = f.getName();
 384  0
         final int i = name.lastIndexOf('.');
 385  0
         if (i > 1) {
 386  0
             name = name.substring(0, i);
 387  
         }
 388  0
         fa.setName(name);
 389  0
         fa.start();
 390  0
         final ch.qos.logback.classic.Logger rootLogger = context.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
 391  0
         rootLogger.addAppender(fa);
 392  0
     }
 393  
 
 394  
     /**
 395  
      * Takes a path and resolves it to be a canonical & absolute path. The caveats are that this method will take an Ant style
 396  
      * file selector path (../someDir/**\/*.jar) and convert it to an absolute/canonical path (at least to the left of the first *
 397  
      * or ?).
 398  
      *
 399  
      * @param path the path to canonicalize
 400  
      * @return the canonical path
 401  
      */
 402  
     protected String ensureCanonicalPath(String path) {
 403  16
         String basePath = null;
 404  16
         String wildCards = null;
 405  16
         final String file = path.replace('\\', '/');
 406  16
         if (file.contains("*") || file.contains("?")) {
 407  
 
 408  8
             int pos = getLastFileSeparator(file);
 409  8
             if (pos < 0) {
 410  0
                 return file;
 411  
             }
 412  8
             pos += 1;
 413  8
             basePath = file.substring(0, pos);
 414  8
             wildCards = file.substring(pos);
 415  8
         } else {
 416  8
             basePath = file;
 417  
         }
 418  
 
 419  16
         File f = new File(basePath);
 420  
         try {
 421  16
             f = f.getCanonicalFile();
 422  16
             if (wildCards != null) {
 423  8
                 f = new File(f, wildCards);
 424  
             }
 425  0
         } catch (IOException ex) {
 426  0
             LOGGER.warn("Invalid path '{}' was provided.", path);
 427  0
             LOGGER.debug("Invalid path provided", ex);
 428  16
         }
 429  16
         return f.getAbsolutePath().replace('\\', '/');
 430  
     }
 431  
 
 432  
     /**
 433  
      * Returns the position of the last file separator.
 434  
      *
 435  
      * @param file a file path
 436  
      * @return the position of the last file separator
 437  
      */
 438  
     private int getLastFileSeparator(String file) {
 439  8
         if (file.contains("*") || file.contains("?")) {
 440  8
             int p1 = file.indexOf('*');
 441  8
             int p2 = file.indexOf('?');
 442  8
             p1 = p1 > 0 ? p1 : file.length();
 443  8
             p2 = p2 > 0 ? p2 : file.length();
 444  8
             int pos = p1 < p2 ? p1 : p2;
 445  8
             pos = file.lastIndexOf('/', pos);
 446  8
             return pos;
 447  
         } else {
 448  0
             return file.lastIndexOf('/');
 449  
         }
 450  
     }
 451  
 }