Coverage Report - org.owasp.dependencycheck.Engine
 
Classes in this File Line Coverage Branch Coverage Complexity
Engine
52%
112/212
55%
39/70
3.25
 
 1  
 /*
 2  
  * This file is part of dependency-check-core.
 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 java.io.File;
 21  
 import java.util.ArrayList;
 22  
 import java.util.EnumMap;
 23  
 import java.util.HashSet;
 24  
 import java.util.Iterator;
 25  
 import java.util.List;
 26  
 import java.util.Set;
 27  
 import java.util.logging.Level;
 28  
 import java.util.logging.Logger;
 29  
 import org.owasp.dependencycheck.analyzer.AnalysisPhase;
 30  
 import org.owasp.dependencycheck.analyzer.Analyzer;
 31  
 import org.owasp.dependencycheck.analyzer.AnalyzerService;
 32  
 import org.owasp.dependencycheck.analyzer.FileTypeAnalyzer;
 33  
 import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
 34  
 import org.owasp.dependencycheck.data.nvdcve.ConnectionFactory;
 35  
 import org.owasp.dependencycheck.data.nvdcve.CveDB;
 36  
 import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
 37  
 import org.owasp.dependencycheck.data.update.CachedWebDataSource;
 38  
 import org.owasp.dependencycheck.data.update.UpdateService;
 39  
 import org.owasp.dependencycheck.data.update.exception.UpdateException;
 40  
 import org.owasp.dependencycheck.dependency.Dependency;
 41  
 import org.owasp.dependencycheck.exception.NoDataException;
 42  
 import org.owasp.dependencycheck.utils.FileUtils;
 43  
 import org.owasp.dependencycheck.utils.InvalidSettingException;
 44  
 import org.owasp.dependencycheck.utils.Settings;
 45  
 
 46  
 /**
 47  
  * Scans files, directories, etc. for Dependencies. Analyzers are loaded and used to process the files found by the
 48  
  * scan, if a file is encountered and an Analyzer is associated with the file type then the file is turned into a
 49  
  * dependency.
 50  
  *
 51  
  * @author Jeremy Long <jeremy.long@owasp.org>
 52  
  */
 53  
 public class Engine {
 54  
 
 55  
     /**
 56  
      * The list of dependencies.
 57  
      */
 58  1
     private List<Dependency> dependencies = new ArrayList<Dependency>();
 59  
     /**
 60  
      * A Map of analyzers grouped by Analysis phase.
 61  
      */
 62  1
     private EnumMap<AnalysisPhase, List<Analyzer>> analyzers = new EnumMap<AnalysisPhase, List<Analyzer>>(AnalysisPhase.class);
 63  
 
 64  
     /**
 65  
      * A Map of analyzers grouped by Analysis phase.
 66  
      */
 67  1
     private Set<FileTypeAnalyzer> fileTypeAnalyzers = new HashSet<FileTypeAnalyzer>();
 68  
 
 69  
     /**
 70  
      * The ClassLoader to use when dynamically loading Analyzer and Update services.
 71  
      */
 72  1
     private ClassLoader serviceClassLoader = Thread.currentThread().getContextClassLoader();
 73  
     /**
 74  
      * The Logger for use throughout the class.
 75  
      */
 76  1
     private static final Logger LOGGER = Logger.getLogger(Engine.class.getName());
 77  
 
 78  
     /**
 79  
      * Creates a new Engine.
 80  
      *
 81  
      * @throws DatabaseException thrown if there is an error connecting to the database
 82  
      */
 83  1
     public Engine() throws DatabaseException {
 84  1
         initializeEngine();
 85  1
     }
 86  
 
 87  
     /**
 88  
      * Creates a new Engine.
 89  
      *
 90  
      * @param serviceClassLoader a reference the class loader being used
 91  
      * @throws DatabaseException thrown if there is an error connecting to the database
 92  
      */
 93  0
     public Engine(ClassLoader serviceClassLoader) throws DatabaseException {
 94  0
         this.serviceClassLoader = serviceClassLoader;
 95  0
         initializeEngine();
 96  0
     }
 97  
 
 98  
     /**
 99  
      * Creates a new Engine using the specified classloader to dynamically load Analyzer and Update services.
 100  
      *
 101  
      * @throws DatabaseException thrown if there is an error connecting to the database
 102  
      */
 103  
     protected final void initializeEngine() throws DatabaseException {
 104  1
         ConnectionFactory.initialize();
 105  1
         loadAnalyzers();
 106  1
     }
 107  
 
 108  
     /**
 109  
      * Properly cleans up resources allocated during analysis.
 110  
      */
 111  
     public void cleanup() {
 112  0
         ConnectionFactory.cleanup();
 113  0
     }
 114  
 
 115  
     /**
 116  
      * Loads the analyzers specified in the configuration file (or system properties).
 117  
      */
 118  
     private void loadAnalyzers() {
 119  1
         if (!analyzers.isEmpty()) {
 120  0
             return;
 121  
         }
 122  10
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 123  9
             analyzers.put(phase, new ArrayList<Analyzer>());
 124  
         }
 125  
 
 126  1
         final AnalyzerService service = new AnalyzerService(serviceClassLoader);
 127  1
         final Iterator<Analyzer> iterator = service.getAnalyzers();
 128  15
         while (iterator.hasNext()) {
 129  14
             final Analyzer a = iterator.next();
 130  14
             analyzers.get(a.getAnalysisPhase()).add(a);
 131  14
             if (a instanceof FileTypeAnalyzer) {
 132  6
                 this.fileTypeAnalyzers.add((FileTypeAnalyzer) a);
 133  
             }
 134  14
         }
 135  1
     }
 136  
 
 137  
     /**
 138  
      * Get the List of the analyzers for a specific phase of analysis.
 139  
      *
 140  
      * @param phase the phase to get the configured analyzers.
 141  
      * @return the analyzers loaded
 142  
      */
 143  
     public List<Analyzer> getAnalyzers(AnalysisPhase phase) {
 144  0
         return analyzers.get(phase);
 145  
     }
 146  
 
 147  
     /**
 148  
      * Get the dependencies identified.
 149  
      *
 150  
      * @return the dependencies identified
 151  
      */
 152  
     public List<Dependency> getDependencies() {
 153  10
         return dependencies;
 154  
     }
 155  
 
 156  
     /**
 157  
      * Sets the dependencies.
 158  
      *
 159  
      * @param dependencies the dependencies
 160  
      */
 161  
     public void setDependencies(List<Dependency> dependencies) {
 162  0
         this.dependencies = dependencies;
 163  0
     }
 164  
 
 165  
     /**
 166  
      * Scans an array of files or directories. If a directory is specified, it will be scanned recursively. Any
 167  
      * dependencies identified are added to the dependency collection.
 168  
      *
 169  
      * @param paths an array of paths to files or directories to be analyzed
 170  
      * @return the list of dependencies scanned
 171  
      *
 172  
      * @since v0.3.2.5
 173  
      */
 174  
     public List<Dependency> scan(String[] paths) {
 175  0
         final List<Dependency> deps = new ArrayList<Dependency>();
 176  0
         for (String path : paths) {
 177  0
             final File file = new File(path);
 178  0
             final List<Dependency> d = scan(file);
 179  0
             if (d != null) {
 180  0
                 deps.addAll(d);
 181  
             }
 182  
         }
 183  0
         return deps;
 184  
     }
 185  
 
 186  
     /**
 187  
      * Scans a given file or directory. If a directory is specified, it will be scanned recursively. Any dependencies
 188  
      * identified are added to the dependency collection.
 189  
      *
 190  
      * @param path the path to a file or directory to be analyzed
 191  
      * @return the list of dependencies scanned
 192  
      */
 193  
     public List<Dependency> scan(String path) {
 194  0
         final File file = new File(path);
 195  0
         return scan(file);
 196  
     }
 197  
 
 198  
     /**
 199  
      * Scans an array of files or directories. If a directory is specified, it will be scanned recursively. Any
 200  
      * dependencies identified are added to the dependency collection.
 201  
      *
 202  
      * @param files an array of paths to files or directories to be analyzed.
 203  
      * @return the list of dependencies
 204  
      *
 205  
      * @since v0.3.2.5
 206  
      */
 207  
     public List<Dependency> scan(File[] files) {
 208  0
         final List<Dependency> deps = new ArrayList<Dependency>();
 209  0
         for (File file : files) {
 210  0
             final List<Dependency> d = scan(file);
 211  0
             if (d != null) {
 212  0
                 deps.addAll(d);
 213  
             }
 214  
         }
 215  0
         return deps;
 216  
     }
 217  
 
 218  
     /**
 219  
      * Scans a list of files or directories. If a directory is specified, it will be scanned recursively. Any
 220  
      * dependencies identified are added to the dependency collection.
 221  
      *
 222  
      * @param files a set of paths to files or directories to be analyzed
 223  
      * @return the list of dependencies scanned
 224  
      *
 225  
      * @since v0.3.2.5
 226  
      */
 227  
     public List<Dependency> scan(Set<File> files) {
 228  0
         final List<Dependency> deps = new ArrayList<Dependency>();
 229  0
         for (File file : files) {
 230  0
             final List<Dependency> d = scan(file);
 231  0
             if (d != null) {
 232  0
                 deps.addAll(d);
 233  
             }
 234  0
         }
 235  0
         return deps;
 236  
     }
 237  
 
 238  
     /**
 239  
      * Scans a list of files or directories. If a directory is specified, it will be scanned recursively. Any
 240  
      * dependencies identified are added to the dependency collection.
 241  
      *
 242  
      * @param files a set of paths to files or directories to be analyzed
 243  
      * @return the list of dependencies scanned
 244  
      *
 245  
      * @since v0.3.2.5
 246  
      */
 247  
     public List<Dependency> scan(List<File> files) {
 248  0
         final List<Dependency> deps = new ArrayList<Dependency>();
 249  0
         for (File file : files) {
 250  0
             final List<Dependency> d = scan(file);
 251  0
             if (d != null) {
 252  0
                 deps.addAll(d);
 253  
             }
 254  0
         }
 255  0
         return deps;
 256  
     }
 257  
 
 258  
     /**
 259  
      * Scans a given file or directory. If a directory is specified, it will be scanned recursively. Any dependencies
 260  
      * identified are added to the dependency collection.
 261  
      *
 262  
      * @param file the path to a file or directory to be analyzed
 263  
      * @return the list of dependencies scanned
 264  
      *
 265  
      * @since v0.3.2.4
 266  
      *
 267  
      */
 268  
     public List<Dependency> scan(File file) {
 269  4
         if (file.exists()) {
 270  4
             if (file.isDirectory()) {
 271  2
                 return scanDirectory(file);
 272  
             } else {
 273  2
                 final Dependency d = scanFile(file);
 274  2
                 if (d != null) {
 275  2
                     final List<Dependency> deps = new ArrayList<Dependency>();
 276  2
                     deps.add(d);
 277  2
                     return deps;
 278  
                 }
 279  
             }
 280  
         }
 281  0
         return null;
 282  
     }
 283  
 
 284  
     /**
 285  
      * Recursively scans files and directories. Any dependencies identified are added to the dependency collection.
 286  
      *
 287  
      * @param dir the directory to scan
 288  
      * @return the list of Dependency objects scanned
 289  
      */
 290  
     protected List<Dependency> scanDirectory(File dir) {
 291  38
         final File[] files = dir.listFiles();
 292  38
         final List<Dependency> deps = new ArrayList<Dependency>();
 293  38
         if (files != null) {
 294  74
             for (File f : files) {
 295  36
                 if (f.isDirectory()) {
 296  36
                     final List<Dependency> d = scanDirectory(f);
 297  36
                     if (d != null) {
 298  36
                         deps.addAll(d);
 299  
                     }
 300  36
                 } else {
 301  0
                     final Dependency d = scanFile(f);
 302  0
                     deps.add(d);
 303  
                 }
 304  
             }
 305  
         }
 306  38
         return deps;
 307  
     }
 308  
 
 309  
     /**
 310  
      * Scans a specified file. If a dependency is identified it is added to the dependency collection.
 311  
      *
 312  
      * @param file The file to scan
 313  
      * @return the scanned dependency
 314  
      */
 315  
     protected Dependency scanFile(File file) {
 316  2
         if (!file.isFile()) {
 317  0
             final String msg = String.format("Path passed to scanFile(File) is not a file: %s. Skipping the file.", file.toString());
 318  0
             LOGGER.log(Level.FINE, msg);
 319  0
             return null;
 320  
         }
 321  2
         final String fileName = file.getName();
 322  2
         final String extension = FileUtils.getFileExtension(fileName);
 323  2
         Dependency dependency = null;
 324  2
         if (extension != null) {
 325  2
             if (supportsExtension(extension)) {
 326  2
                 dependency = new Dependency(file);
 327  2
                 dependencies.add(dependency);
 328  
             }
 329  
         } else {
 330  0
             final String msg = String.format("No file extension found on file '%s'. The file was not analyzed.", file.toString());
 331  0
             LOGGER.log(Level.FINE, msg);
 332  
         }
 333  2
         return dependency;
 334  
     }
 335  
 
 336  
     /**
 337  
      * Runs the analyzers against all of the dependencies.
 338  
      */
 339  
     public void analyzeDependencies() {
 340  1
         boolean autoUpdate = true;
 341  
         try {
 342  1
             autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE);
 343  0
         } catch (InvalidSettingException ex) {
 344  0
             LOGGER.log(Level.FINE, "Invalid setting for auto-update; using true.");
 345  1
         }
 346  1
         if (autoUpdate) {
 347  0
             doUpdates();
 348  
         }
 349  
 
 350  
         //need to ensure that data exists
 351  
         try {
 352  1
             ensureDataExists();
 353  0
         } catch (NoDataException ex) {
 354  0
             final String msg = String.format("%s%n%nUnable to continue dependency-check analysis.", ex.getMessage());
 355  0
             LOGGER.log(Level.SEVERE, msg);
 356  0
             LOGGER.log(Level.FINE, null, ex);
 357  0
             return;
 358  0
         } catch (DatabaseException ex) {
 359  0
             final String msg = String.format("%s%n%nUnable to continue dependency-check analysis.", ex.getMessage());
 360  0
             LOGGER.log(Level.SEVERE, msg);
 361  0
             LOGGER.log(Level.FINE, null, ex);
 362  0
             return;
 363  
 
 364  1
         }
 365  
 
 366  1
         final String logHeader = String.format("%n"
 367  
                 + "----------------------------------------------------%n"
 368  
                 + "BEGIN ANALYSIS%n"
 369  
                 + "----------------------------------------------------");
 370  1
         LOGGER.log(Level.FINE, logHeader);
 371  1
         LOGGER.log(Level.INFO, "Analysis Starting");
 372  
 
 373  
         // analysis phases
 374  10
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 375  9
             final List<Analyzer> analyzerList = analyzers.get(phase);
 376  
 
 377  9
             for (Analyzer a : analyzerList) {
 378  14
                 a = initializeAnalyzer(a);
 379  
 
 380  
                 /* need to create a copy of the collection because some of the
 381  
                  * analyzers may modify it. This prevents ConcurrentModificationExceptions.
 382  
                  * This is okay for adds/deletes because it happens per analyzer.
 383  
                  */
 384  14
                 final String msg = String.format("Begin Analyzer '%s'", a.getName());
 385  14
                 LOGGER.log(Level.FINE, msg);
 386  14
                 final Set<Dependency> dependencySet = new HashSet<Dependency>();
 387  14
                 dependencySet.addAll(dependencies);
 388  14
                 for (Dependency d : dependencySet) {
 389  28
                     boolean shouldAnalyze = true;
 390  28
                     if (a instanceof FileTypeAnalyzer) {
 391  12
                         final FileTypeAnalyzer fAnalyzer = (FileTypeAnalyzer) a;
 392  12
                         shouldAnalyze = fAnalyzer.supportsExtension(d.getFileExtension());
 393  
                     }
 394  28
                     if (shouldAnalyze) {
 395  20
                         final String msgFile = String.format("Begin Analysis of '%s'", d.getActualFilePath());
 396  20
                         LOGGER.log(Level.FINE, msgFile);
 397  
                         try {
 398  20
                             a.analyze(d, this);
 399  0
                         } catch (AnalysisException ex) {
 400  0
                             final String exMsg = String.format("An error occurred while analyzing '%s'.", d.getActualFilePath());
 401  0
                             LOGGER.log(Level.WARNING, exMsg);
 402  0
                             LOGGER.log(Level.FINE, "", ex);
 403  0
                         } catch (Throwable ex) {
 404  0
                             final String axMsg = String.format("An unexpected error occurred during analysis of '%s'", d.getActualFilePath());
 405  
                             //final AnalysisException ax = new AnalysisException(axMsg, ex);
 406  0
                             LOGGER.log(Level.WARNING, axMsg);
 407  0
                             LOGGER.log(Level.FINE, "", ex);
 408  20
                         }
 409  
                     }
 410  28
                 }
 411  14
             }
 412  
         }
 413  10
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 414  9
             final List<Analyzer> analyzerList = analyzers.get(phase);
 415  
 
 416  9
             for (Analyzer a : analyzerList) {
 417  14
                 closeAnalyzer(a);
 418  14
             }
 419  
         }
 420  
 
 421  1
         final String logFooter = String.format("%n"
 422  
                 + "----------------------------------------------------%n"
 423  
                 + "END ANALYSIS%n"
 424  
                 + "----------------------------------------------------");
 425  1
         LOGGER.log(Level.FINE, logFooter);
 426  1
         LOGGER.log(Level.INFO, "Analysis Complete");
 427  1
     }
 428  
 
 429  
     /**
 430  
      * Initializes the given analyzer.
 431  
      *
 432  
      * @param analyzer the analyzer to initialize
 433  
      * @return the initialized analyzer
 434  
      */
 435  
     protected Analyzer initializeAnalyzer(Analyzer analyzer) {
 436  
         try {
 437  14
             final String msg = String.format("Initializing %s", analyzer.getName());
 438  14
             LOGGER.log(Level.FINE, msg);
 439  14
             analyzer.initialize();
 440  0
         } catch (Throwable ex) {
 441  0
             final String msg = String.format("Exception occurred initializing %s.", analyzer.getName());
 442  0
             LOGGER.log(Level.SEVERE, msg);
 443  0
             LOGGER.log(Level.FINE, null, ex);
 444  
             try {
 445  0
                 analyzer.close();
 446  0
             } catch (Throwable ex1) {
 447  0
                 LOGGER.log(Level.FINEST, null, ex1);
 448  0
             }
 449  14
         }
 450  14
         return analyzer;
 451  
     }
 452  
 
 453  
     /**
 454  
      * Closes the given analyzer.
 455  
      *
 456  
      * @param analyzer the analyzer to close
 457  
      */
 458  
     protected void closeAnalyzer(Analyzer analyzer) {
 459  14
         final String msg = String.format("Closing Analyzer '%s'", analyzer.getName());
 460  14
         LOGGER.log(Level.FINE, msg);
 461  
         try {
 462  14
             analyzer.close();
 463  0
         } catch (Throwable ex) {
 464  0
             LOGGER.log(Level.FINEST, null, ex);
 465  14
         }
 466  14
     }
 467  
 
 468  
     /**
 469  
      * Cycles through the cached web data sources and calls update on all of them.
 470  
      */
 471  
     private void doUpdates() {
 472  0
         LOGGER.info("Checking for updates");
 473  0
         final UpdateService service = new UpdateService(serviceClassLoader);
 474  0
         final Iterator<CachedWebDataSource> iterator = service.getDataSources();
 475  0
         while (iterator.hasNext()) {
 476  0
             final CachedWebDataSource source = iterator.next();
 477  
             try {
 478  0
                 source.update();
 479  0
             } catch (UpdateException ex) {
 480  0
                 LOGGER.log(Level.WARNING,
 481  
                         "Unable to update Cached Web DataSource, using local data instead. Results may not include recent vulnerabilities.");
 482  0
                 LOGGER.log(Level.FINE, String.format("Unable to update details for %s", source.getClass().getName()), ex);
 483  0
             }
 484  0
         }
 485  0
         LOGGER.info("Check for updates complete");
 486  0
     }
 487  
 
 488  
     /**
 489  
      * Returns a full list of all of the analyzers. This is useful for reporting which analyzers where used.
 490  
      *
 491  
      * @return a list of Analyzers
 492  
      */
 493  
     public List<Analyzer> getAnalyzers() {
 494  0
         final List<Analyzer> ret = new ArrayList<Analyzer>();
 495  0
         for (AnalysisPhase phase : AnalysisPhase.values()) {
 496  0
             final List<Analyzer> analyzerList = analyzers.get(phase);
 497  0
             ret.addAll(analyzerList);
 498  
         }
 499  0
         return ret;
 500  
     }
 501  
 
 502  
     /**
 503  
      * Checks all analyzers to see if an extension is supported.
 504  
      *
 505  
      * @param ext a file extension
 506  
      * @return true or false depending on whether or not the file extension is supported
 507  
      */
 508  
     public boolean supportsExtension(String ext) {
 509  851
         if (ext == null) {
 510  3
             return false;
 511  
         }
 512  848
         boolean scan = false;
 513  848
         for (FileTypeAnalyzer a : this.fileTypeAnalyzers) {
 514  
             /* note, we can't break early on this loop as the analyzers need to know if
 515  
              they have files to work on prior to initialization */
 516  5088
             scan |= a.supportsExtension(ext);
 517  5088
         }
 518  848
         return scan;
 519  
     }
 520  
 
 521  
     /**
 522  
      * Returns the set of file type analyzers.
 523  
      *
 524  
      * @return the set of file type analyzers
 525  
      */
 526  
     public Set<FileTypeAnalyzer> getFileTypeAnalyzers() {
 527  0
         return this.fileTypeAnalyzers;
 528  
     }
 529  
 
 530  
     /**
 531  
      * Checks the CPE Index to ensure documents exists. If none exist a NoDataException is thrown.
 532  
      *
 533  
      * @throws NoDataException thrown if no data exists in the CPE Index
 534  
      * @throws DatabaseException thrown if there is an exception opening the database
 535  
      */
 536  
     private void ensureDataExists() throws NoDataException, DatabaseException {
 537  1
         final CveDB cve = new CveDB();
 538  
         try {
 539  1
             cve.open();
 540  1
             if (!cve.dataExists()) {
 541  0
                 throw new NoDataException("No documents exist");
 542  
             }
 543  0
         } catch (DatabaseException ex) {
 544  0
             throw new NoDataException(ex.getMessage(), ex);
 545  
         } finally {
 546  1
             cve.close();
 547  1
         }
 548  1
     }
 549  
 }